Cyber Week

Save big!

All courses under $5 - for a limited time!

Code has been added to clipboard!

PHP count()

Reading time 2 min
Published Aug 14, 2017
Updated Oct 10, 2019

PHP Array Length: Main Tips

  • This function is used to get the number of elements in an array (in other words, to get PHP array length).
  • Introduced in PHP 4, though mode parameter used for multidimensional arrays only appeared in PHP 4.2.

count() Function

To get you started, we'll view a simple example. In it, we have an array called $fruits. Using PHP count()function, we will be able to easily count the elements in contains, or define PHP array length:

Example
<?php
  $fruits = ['Banana', 'Cherry', 'Apple'];
  echo "Result: " . count($fruits);
?>
Theory is great, but we recommend digging deeper!

Learn Proper Syntax

If we wish our PHP count() function to work and let us get PHP array length easily, we should follow the syntax described below:

count(array, mode);

The parameters are explained in more detail in the table that follows:

Parameter Description
array Necessary. Specifies the array to count.
mode Optional. Specifies PHP array length counting mode:
0 - Default. Only counts elements in a particular array.
1 - Counts elements in all arrays a multidimensional array contains.

Counting Examples

The example we have here is meant to show you the difference between different PHP array size counting modes. In it, $fruits is a multidimensional array that contains three arrays that have seven elements between them. Using different modes fetches us different PHP array sizes:

Example
<?php
   $fruit = [
      'Banana' => ['Green', 'Yellow'],
      'Apple' => ['Green', 'Yellow', 'Red'],
      'Berry' => ['Blueberry', 'Strawberry']
   ]; 
   echo "Normal count: " . count($fruit)."<br>";
   echo "Multidimensional count: " . count($fruit, 1);
?>

Let's see a few more examples of getting PHP array length using count():

Example
<?php
   $fruit = [
      'Banana' => ['Green', 'Yellow'],
      'Apple' => ['Green', 'Yellow', 'Red'],
      'Berry' => ['Blueberry', 'Strawberry']
   ]; 
   echo "Normal count: " . count($fruit)."<br>";
   echo "Multidimensional count: " . count($fruit, 1);
?>
Example
<?php
   $fruits = ['Banana', 'Cherry', 'Peach'];
   $array_length = count($fruits);
   echo "Result: " . $array_length;
?>