Posted by Arjun Arjun on Tuesday 24th January 2012, 1 minute read

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
...
Arjun

I am Arjun from Hyderabad (India). I have been working as a software engineer from the last 7+ years, and it is my passion to learn new things and implement them as a practice. Aside from work, I like gardening and spending time with pets.