This is a beginner’s guide on how to get the length of a PHP array. To count all of the elements in a PHP array, you can either use the count function or the sizeof function.
Counting the number of elements in a PHP array.
Do NOT use a loop to count the number of elements in array, as this would be extremely wasteful.
To count the number of elements in an array, you can use PHP’s native count function like so:
//An array of names.
$names = array(
//Get the number of elements in the array by
//using PHP's inbuilt count() function.
$numElements = count($names);
//Print it out.
If you run the code snippet above, you will find that the output of count() is “5”. This is because there is five elements in the $names array.
Counting elements in a multidimensional array.
In some cases, you might need to count all of the elements in a multidimensional PHP array. To do this, you will need to use the count function’s second parameter, which is called mode.
To achieve this, we can simply pass the constant COUNT_RECURSIVE in as the second parameter:
//A multidimensional array.
$arr = array(
//Pass COUNT_RECURSIVE in as a second parameter.
$numElements = count($arr, COUNT_RECURSIVE);
//Print out the result
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 element (you’d be surprised by how many developers expect the length to be 6).
The 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 stick to using the count function. This is because other programmers may expect the sizeof function to return the size of the array in bytes / memory.
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.