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:

  1. Line 3: We set the $drinks variable to an array of items.

  2. Line 5: We use the count function to calculate the size of the array. Then we print the result using the echo command.

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:

  1. Line 3: We set the $drinks variable to an array of values, one of which is a secondary array.

  2. Line 11: We use the count function to calculate the size of the $drinks array. As we call count with the COUNT_RECURSIVE argument, 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:

  1. Line 3: We set the $invalidArgument variable to the value 100.

  2. Line 5: We try to call the count function with the $invalidArgument variable.