In php, we can get the length of an array easiest with the php count() function.
$array = array(1, 2, 3, 4, 5);
echo count($array);
// Output:
5
When working with arrays in php, it can be valuable to be able to easily gather information of the properties of an array.
One such situation is when you want to get the size of an array.
To get the length of an array, you can use the php count() function.
Just pass an array to count() to get the count of the number of elements in the array.
Below is a simple example in php of how to use the count() function to get the length of an array.
$array = array(1, 2, 3, 4, 5);
echo count($array);
// Output:
5
Find the Size of an Array with sizeof() Function in php
Another function which is useful in php is the sizeof() function. The sizeof() function is an alias of count().
You can use the sizeof() function to get the size of an array, but it is better to use count() to find the length of an array.
Below is an example in php showing that sizeof() returns the same count as count().
$array = array(1, 2, 3, 4, 5);
echo sizeof($array);
// Output:
5
Using count() to Count the Number of Elements in a Multi-Dimensional Array in php
With the php count() function, we can do more than just find the length of a one-dimensional array.
We can also get the size of a multi-dimensional array by passing ‘COUNT_RECURSIVE’ to the optional ‘mode’ parameter.
The ‘COUNT_RECURSIVE’ option counts the number of elements recursively and will go into any sub arrays to get the length and size of those arrays.
Below is an example in php of how you can use ‘COUNT_RECURSIVE’ to get the number of elements of a multi-dimensional array.
$array = array(1, 2, array(3, 4, 5), 6, 7);
var_dump(count($array));
var_dump(count($array, COUNT_RECURSIVE));
//Output:
int(5)
int(8)
As shown above, when we don’t pass ‘COUNT_RECURSIVE’, we get the length of the array’s first dimension. But after passing ‘COUNT_RECURSIVE’, we get the total number of elements.
Hopefully this article has been useful for you to learn how to use the php count() function to get an array’s length in php.