Often it’s useful to know how many elements an array contains. Here are some common reasons for counting the number of elements in an array:
- You can then use a
for
loop to move through the elements - You can display the total number of elements to the user (such as the number of search results returned)
- You can calculate the average of the values in the array (in conjunction with
array_sum()
)
PHP makes it easy to count array elements, thanks to its built-in count()
function. In this tutorial you’ll learn how to use count()
to count the elements in both regular and multidimensional arrays, and how to move through all the elements of an indexed array by using count()
and a for
loop.
[Read more…] about Counting PHP Array Elements Using count()