Using PHP count() Function to Determine Array and Object Lengths
This article explains PHP's count() function, its syntax and parameters, and provides step‑by‑step examples for counting simple and multidimensional arrays using both normal and recursive modes. It also shows how to output the results and highlights the differences between COUNT_NORMAL and COUNT_RECURSIVE.
In PHP, the count() function is used to count the number of elements in an array or the number of properties in an object, providing a quick way to obtain length for further operations.
The syntax is:
count($array, $mode = COUNT_NORMAL)Parameter description:
$array : required, the array or object whose length is to be counted.
$mode : optional, determines counting mode. Default COUNT_NORMAL counts only top‑level elements; COUNT_RECURSIVE counts elements recursively across all dimensions.
Below are concrete code examples demonstrating the use of count() :
Example 1: Counting the length of a simple array
First we create an array with several elements and use count() to obtain its length:
Output:
Array $fruits length is: 4The code defines the $fruits array with four items, calls count($fruits) , stores the result in $length , and echoes it.
Example 2: Counting the length of a multidimensional array
Now we create a two‑dimensional array and calculate its length using both COUNT_NORMAL and COUNT_RECURSIVE modes:
"Tom", "age" => 20),
array("name" => "John", "age" => 22),
array("name" => "Alice", "age" => 18)
);
$length_normal = count($students); // COUNT_NORMAL
$length_recursive = count($students, COUNT_RECURSIVE); // COUNT_RECURSIVE
echo "Array $students length (COUNT_NORMAL): " . $length_normal . "
";
echo "Array $students length (COUNT_RECURSIVE): " . $length_recursive;
?>Output:
Array $students length (COUNT_NORMAL): 3
Array $students length (COUNT_RECURSIVE): 6Here $students is a two‑dimensional array containing three sub‑arrays. Using count($students) with COUNT_NORMAL returns 3, while COUNT_RECURSIVE returns 6, counting all nested elements.
Summary
The count() function is a versatile PHP tool for determining the size of arrays or objects. By selecting the appropriate mode parameter, developers can count only top‑level elements or recursively count every element across all dimensions.
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.