Get the length of a PHP array

To get the length of a PHP array, you can use the count function or the sizeof function.

Both functions do the exact same thing, as sizeof is merely an alias of count.

Getting the length of a PHP array.

Do not use a loop to count the number of elements in an array, as doing so would be extremely wasteful.

To get the length of a PHP array, you can use the count function:

//An array of names.
$names = array(
    'John',
    'Jason',
    'Martina',
    'Lisa',
    'Tony'
);

//Get the number of elements in the array by
//using PHP's count() function.
$numElements = count($names);

//Print the result
echo $numElements;

If you run the code above, you will find that the output isĀ “5”. This is because there are five elements in the $names array.

Get the length of a multidimensional array.

In some cases, you may need to get the length of a multidimensional PHP array. To do this, you will need to pass the constant COUNT_RECURSIVE in as the count’s second parameter.

//A multidimensional array.
$arr = array(
    1,
    2,
    10,
    array(
        20,
        21,
        80
    )
);

//Pass COUNT_RECURSIVE in as the second parameter.
$numElements = count($arr, COUNT_RECURSIVE);

//Print the result
echo $numElements;

Note that the code above will print out “7” instead of “6”. This is because the array containing 20, 21, and 80 is also considered to be an individual element.

There is no difference between count and sizeof.

The count function and the sizeof function do the exact same thing. In fact, sizeof is merely an alias of the count function.

Personally, I would suggest that you use the count function. This is because programmers from other languages may expect the sizeof function to return the size of the array in bytes.

Note that as of PHP 7.2, the count function will emit an E_WARNING error if you provide it with a variable that isn’t an array or a Countable object.