How to count the elements of a multidimensional array in PHP?

The count() function counts only the first level of an array. To count all elements including the inner arrays, pass COUNT_RECURSIVE as the second parameter.

<?php
$cars = [
    ["Volvo", 22, 18],
    ["BMW", 15, 13]
];

echo count($cars) . "<br>";
echo count($cars, COUNT_RECURSIVE);
?>

Output:

Tutorials Class - Output Window

2
8

The first line counts the 2 inner arrays. The recursive count adds 6 inner values to them, so it is 8. The function sizeof() is only an alias of count().


Learn more about the similar topics:
Tutorials
No Content Found.
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.