How to Count All the Array Elements with PHP
While working with arrays, it is commonly necessary to count all its elements. This snippet will discover two helpful functions that will help you do that.
Suppose, you have an array that includes several elements, and you need to count all of them with the help of PHP. Here, we will represent two handy methods to do that.
Using the count() Function
The count() function counts all the current elements inside an array. In the case of an empty array, it returns 0.
The syntax is shown below:
php count() function syntax
<?php
count($array, mode);
?>If the optional mode parameter is set to COUNT_RECURSIVE (or 1), count() will recursively count the number of elements inside the array. This is especially useful for counting all elements in multidimensional arrays.
And, here is an example:
php count() function example
<?php
// PHP program for counting all the elements
// or values inside an array
// Using the count() function
$array = ["W3docs1", "W3docs2", "W3docs3", "1", "2", "3"];
echo "Count first array elements: " . count($array) . "\n";
$array = [
'names' => ["W3docs1", "W3docs2", "W3docs3"],
'rank' => ['1', '2', '3'],
];
echo "Recursive count: " . count($array, COUNT_RECURSIVE) . "\n";
echo "Normal count: " . count($array, 0);
?>php using count() function, output
Count first array elements: 6
Recursive count: 8
Normal count: 2Using the sizeof() Function
This function is an alias for count() and was historically used for counting the number of elements inside an array or another countable object. However, sizeof() was deprecated in PHP 7.2 and removed in PHP 8.0. For modern development, you should always use count() instead.
The syntax used for this function is as follows:
php sizeof() function syntax
<?php
sizeof($array, mode);
?>Sizeof() is the alias of count(). Note that this alias is no longer available in PHP 8.0+.
To be more precise, let’s see an example:
php sizeof() function usage
<?php
// PHP program for counting all the elements
// or values inside an array
// Use of sizeof() function
$array = ["W3docs1", "W3docs2", "W3docs3", "1", "2", "3"];
echo "Count second array elements: " . sizeof($array) . "\n";
$array = [
'names' => ["W3docs1", "W3docs2", "W3docs3"],
'rank' => ['1', '2', '3'],
];
echo "Recursive count: " . sizeof($array, 1) . "\n";
echo "Normal count: " . sizeof($array, 0) . "\n";
?>After using the <kbd class="highlighted">sizeof()</kbd> function, you will have the following output:
Count second array elements: 6
Recursive count: 8
Normal count: 2Above, we represented two helpful functions that can be used for counting the elements of an array in PHP. While both were historically easy to use, count() is the standard and recommended approach for all modern PHP versions.