Posted by Arjun on Tuesday 24th January 2012

How to count the number of items in a PHP array ?

Here is my Array with some stuff

   $myArray = array('key1' => 'value1',
                    'key2' => 'value2',
                    'key3' => 'value3');

What if you need to count the number of array members, we can achieve this with PHP function called count().

How to Use:

  $result = count($example);
echo $result; // output 3

What about a recursive count for multidimensional arrays? Well, it works in a very similar way, only we must specify the COUNT_RECURSIVE parameter

Example :

 $food = array('fruits' => array('orange', 'banana', 'apple'),
              'veggie' => array('carrot', 'collard', 'pea'));

// recursive count
echo count($food, COUNT_RECURSIVE); // output 8

// normal count
echo count($food); // output 2