• Skip to main content
  • Skip to primary sidebar
  • Skip to footer

Matt Doyle | Elated Communications

Web and WordPress Development

  • About Me
  • Blog
    • Design & Multimedia
      • Photoshop
      • Paint Shop Pro
      • Video & Audio
    • Online Marketing
      • E-Commerce
      • Social Media
    • Running a Website
      • WordPress
      • Apache
      • UNIX and Linux
      • Using FTP
    • Web Development
      • HTML
      • CSS
      • JavaScript
      • PHP
      • Perl and CGI Scripting
  • Portfolio
  • Contact Me
  • Hire Me
Home / Blog / Web Development / PHP / PHP Arrays / Counting PHP Array Elements Using count()

Counting PHP Array Elements Using count()

6 May 2010 / Leave a Comment

Counting PHP Array Elements Using count()

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() and for to loop through the elements in an array
  • To be careful when using count() and for on arrays with non-contiguous indices
  • A bit more about multidimensional arrays, and how to count all their elements using count()

Happy coding!

Filed Under: PHP Arrays Tagged With: array, count, for, index, indices, loop, multidimensional, php, recursive

Reader Interactions

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

To include a block of code in your comment, surround it with <pre> ... </pre> tags. You can include smaller code snippets inside some normal text by surrounding them with <code> ... </code> tags.

Allowed tags in comments: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre> .

Primary Sidebar

Hire Matt!

Matt Doyle headshot

Need a little help with your website? I have over 20 years of web development experience under my belt. Let’s chat!

Matt Doyle - Codeable Expert Certificate

Hire Me Today

Call Me: +61 2 8006 0622

Stay in Touch!

Subscribe to get a quick email whenever I add new articles, free goodies, or special offers. I won’t spam you.

Subscribe

Recent Posts

  • Make a Rotatable 3D Product Boxshot with Three.js
  • Speed Up Your WordPress Website: 11 Simple Steps to a Faster Site
  • Reboot!
  • Wordfence Tutorial: How to Keep Your WordPress Site Safe from Hackers
  • How to Make Awesome-Looking Images for Your Website

Footer

Contact Matt

  • Email Me
  • Call Me: +61 2 8006 0622

Follow Matt

  • E-mail
  • Facebook
  • GitHub
  • LinkedIn
  • Twitter

Copyright © 1996-2023 Elated Communications. All rights reserved.
Affiliate Disclaimer | Privacy Policy | Terms of Use | Service T&C | Credits