Easy way to check PHP array length

If you want to know how many elements are there in a PHP array, you can get the number of elements of an array with the help of the count() or sizeof() function. The sizeof() is alias of the count().

Syntax of the PHP Count/Sizeof function

The count() function takes two parameters, and it returns the number of array elements.

count(array, mode)
  1. array – The array which length you want to know.
  2. mode – It is optional, and by default it is 0;
    • 0 – Does not count the elements inside multidimensional arrays.
    • 1 – Counts all the elements, including elements of multidimensional arrays.
<?php
//    1   2   3   4
$a = [21, 32, 54, [75, 85]];

echo "<pre>";
echo count($a);
echo "\n";
echo sizeof($a);
echo "</pre>";
4
4

Example with mode=1

<?php
$a = [21, 32, 54, [75, 85]];

echo "<pre>";
echo count($a, 1);
echo "\n";
echo sizeof($a, 1);
echo "</pre>";
6
6
php multidimensional array count with mode 1

Leave a Reply

Your email address will not be published. Required fields are marked *