Join my Laravel for REST API's course on Udemy 👀

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.

<?php

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.

<?php

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.

<?php

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