We use array count and length to find out how many items are inside an array. This helps us understand the size of the array.
Array count and length in PHP
<?php // Define an array $array = [1, 2, 3, 4]; // Get the number of elements $count = count($array); // Print the count echo $count; ?>
Use the count() function to get the number of elements in an array.
PHP arrays do not have a separate length property like some other languages; use count() instead.
<?php // Empty array $emptyArray = []; echo count($emptyArray); // Output: 0 ?>
<?php // Array with one element $singleElementArray = ['apple']; echo count($singleElementArray); // Output: 1 ?>
<?php // Array with multiple elements $fruits = ['apple', 'banana', 'cherry']; echo count($fruits); // Output: 3 ?>
<?php // Associative array $person = ['name' => 'John', 'age' => 30]; echo count($person); // Output: 2 ?>
This program shows how to count elements in an array before and after adding a new item.
<?php // Create an array of colors $colors = ['red', 'green', 'blue']; // Print the array before counting echo "Colors array before counting:\n"; print_r($colors); // Get the count of elements $numberOfColors = count($colors); // Print the count echo "Number of colors: $numberOfColors\n"; // Add a new color $colors[] = 'yellow'; // Print the array after adding echo "Colors array after adding a new color:\n"; print_r($colors); // Get the new count $numberOfColors = count($colors); // Print the new count echo "Number of colors now: $numberOfColors\n"; ?>
The count() function runs in O(1) time because PHP stores the size internally.
Memory use is minimal since count() does not copy the array.
A common mistake is to try to use sizeof() as a property; it is a function like count().
Use count() when you need the number of elements; use loops or other functions to access elements.
count() tells you how many items are in an array.
It works for empty, single, multiple, and associative arrays.
Use it before looping or when you need to check if an array has items.