Now Explains how to use PHP’s count() function to count the elements in an array, and how to loop through an array with count() and a for loop.
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:
<?php $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:
<?php $movie = array( "title" => "Rear Window", "director" => "Alfred Hitchcock", "year" => 1954, "minutes" => 112 ); // Displays "4" echo count( $movie ); ?>
0 comments:
Post a Comment