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.
Basic count()
usage
Using count()
is easy. Just pass it the array whose elements you want to count, and the function returns the number of elements in the array:
$directors = array( "Alfred Hitchcock", "Stanley Kubrick", "Martin Scorsese", "Fritz Lang" );
// Displays "4"
echo count( $directors );
The above example counts the elements in an indexed array, but you can just as easily count an associative array:
$movie = array( "title" => "Rear Window",
"director" => "Alfred Hitchcock",
"year" => 1954,
"minutes" => 112 );
// Displays "4"
echo count( $movie );
Moving through arrays with count()
and for
loops
You can use count()
, along with your knowledge of for
loops and working with array elements, to loop through all the elements in an indexed array:
$directors = array( "Alfred Hitchcock", "Stanley Kubrick", "Martin Scorsese", "Fritz Lang" );
// Displays "Alfred Hitchcock, Stanley Kubrick, Martin Scorsese, Fritz Lang":
$totalElements = count( $directors );
for ( $i=0; $i < $totalElements; $i++ ) {
echo $directors[$i];
if ( $i < $totalElements -1 ) echo ", ";
}
The above code first reads the total number of array elements using count()
, and stores the result (4) in $totalElements
. It then loops through each element index, from 0 through to $totalElements - 1
(i.e. 3), displaying the element’s value as it goes. (The if
statement displays a comma and space after each element except for the last.)
You do need to be bit careful when using count()
with for
. As you saw in Creating Arrays in PHP, PHP doesn’t distinguish between indexed and associative arrays, and numeric array indices don’t have to be contiguous either. Consider the following example:
error_reporting(E_ALL);
ini_set( 'display_errors', true );
$directors = array( 0 => "Alfred Hitchcock", 1 => "Stanley Kubrick", 2 => "Martin Scorsese", 39 => "Fritz Lang" );
// Displays "Alfred Hitchcock, Stanley Kubrick, Martin Scorsese,"
// and generates an "Undefined offset: 3" notice:
$totalElements = count( $directors );
for ( $i=0; $i < $totalElements; $i++ ) {
echo $directors[$i];
if ( $i < $totalElements -1 ) echo ", ";
}
What’s happening here? The above example is identical to the one before, except that the array indices are no longer contiguous (0, 1, 2, and 39). We’ve also set PHP to display all errors in the browser. When the code tries to read the element with the index of 3, PHP generates an “Undefined offset” notice because an element with this index doesn’t exist.
The lesson here is that count() - 1
only equals the index of the last element in the array when the array indices are contiguously numbered (for example, 0, 1, 2 and 3). Fortunately, this is usually the case with indexed arrays.
If you’re not sure whether the indices of an array are contiguous, you can use other PHP constructs such as foreach
to loop through the array’s elements. (More on foreach
in a later tutorial.)
Counting multidimensional arrays
We touched briefly on multidimensional arrays in Creating Arrays in PHP. Essentially, a multidimensional array is an array whose elements are also arrays.
By default, count()
only counts the elements in the top level of a multidimensional array. Here’s an example:
$movieInfo = array( "directors" => array( "Alfred Hitchcock", "Stanley Kubrick", "Martin Scorsese", "Fritz Lang" ),
"movies" => array( "Rear Window", "2001", "Taxi Driver", "Metropolis" ) );
// Displays "2"
echo count( $movieInfo );
The above code only counts the 2 elements in the top-level array ("directors"
and "movies"
).
If you want to count all the elements in a multidimensional array — that is, not just the top-level elements, but the elements in all arrays inside the array — then pass the constant COUNT_RECURSIVE
as a second argument to count()
:
$movieInfo = array( "directors" => array( "Alfred Hitchcock", "Stanley Kubrick", "Martin Scorsese", "Fritz Lang" ),
"movies" => array( "Rear Window", "2001", "Taxi Driver", "Metropolis" ) );
// Displays "10"
echo count( $movieInfo, COUNT_RECURSIVE );
In the above example, count()
first counts the 2 elements in the top-level array ("directors"
and "movies"
). Then it counts all 8 elements in the nested arrays ("Alfred Hitchcock"
to "Fritz Lang"
, then "Rear Window"
to "Metropolis"
). This results in a grand total of 10 elements.
Summary
In this tutorial, you’ve explored PHP’s count()
function for counting the number of elements in an array. You’ve also learned:
- How to use
count()
andfor
to loop through the elements in an array - To be careful when using
count()
andfor
on arrays with non-contiguous indices - A bit more about multidimensional arrays, and how to count all their elements using
count()
Happy coding!
Leave a Reply