How to find the length of a PHP array
In PHP, we can use the count function to find the length of an array. It accepts an array as its argument and returns an integer. The count function has been available since PHP version 4.
<?php$drinks = ['Espresso', 'Americano'];echo count($drinks);
Let’s look at the code in detail:
-
Line 3: We set the
$drinksvariable to an array of items. -
Line 5: We use the
countfunction to calculate the size of the array. Then we print the result using theechocommand.
How to count an array recursively
The count function accepts an optional second argument called the count mode. The default value is COUNT_NORMAL. We can provide the value COUNT_RECURSIVE in order to count nested arrays.
Calling count with COUNT_RECURSIVE mode will include both the number of nested arrays as well as the number of elements in the total count. Try the example below where the count function will return the value 4, representing tree elements, plus one nested array.
<?php$drinks = ['Espresso','Americano',['Water']];echo count($drinks, COUNT_RECURSIVE);
Let’s look at the code in detail:
-
Line 3: We set the
$drinksvariable to an array of values, one of which is a secondary array. -
Line 11: We use the
countfunction to calculate the size of the$drinksarray. As we callcountwith theCOUNT_RECURSIVEargument, it will include nested items in the result.
Different behavior of count function across PHP versions
The count function accepts an array or any object that implements the Countable interface.
In PHP 8, providing an invalid argument to the count function will result in a TypeError being thrown. However, in PHP 7.2 and earlier versions, it would generate a warning. To demonstrate this behavior, try the example below, which is compatible with PHP 7.4.
<?php$invalidArgument = 100;echo count($invalidArgument);
Let’s look at the code in detail:
-
Line 3: We set the
$invalidArgumentvariable to the value100. -
Line 5: We try to call the
countfunction with the$invalidArgumentvariable.