Skip to content

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

Last updated on January 17, 2018

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
0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments