Get the length of an array in PHP

June 17, 2022  ‐ 1 min read

To find the amount of elements in an array we use the PHP array function count().

In its most basic form we can call the count() function with an array as its first argument and it returns the number of elements in the array.


echo count(['a', 'b', 'c']);
//=> 3

For associative arrays we can use the same count function as well to get the amount of values it contains.


echo count([
    'a' => 'b',
    'c' => 'd',
//=> 2

Where it gets interesting is the recursive counting option that is provided. This allows to not just count the plain values, but also the contents of nested arrays.

The value returned might seem unintuitive, since both the array and its contents are included in the count.


echo count([
    'a' => ['b', 'c', 'd'],
    'e' => 'f',
//=> 5