Ruwansiri Pathirana
Ruwansiri Pathirana

Reputation: 31

How to count a multidimensional array

$fruits = array("banana", "pineapple", array("apple", "mango"), "guava");
echo count($fruits,1);

The above code outputs 6, but I don't understand why. Can someone please explain it?

Upvotes: 2

Views: 175

Answers (5)

Emilio Gort
Emilio Gort

Reputation: 3470

$fruits = array("banana", "pineapple", array("apple", "mango"), "guava");

Because is counting the array("apple","mango") as 1 element

count($fruits,1)// the second parameter will recursively count the array

+ 1 -> banana
+ 1 -> pineapple
+ 1 -> array("apple","mango")
+ 1 --------> apple
+ 1 --------> mango
+ 1 -> guava
____
 6 elements

Upvotes: 1

Aurelien
Aurelien

Reputation: 1507

array("apple","mango") counts as 3, since you're deep counting.

It first counts "banana", "pineapple", array(), "guava" Then "apple" and "mango"

Upvotes: 0

Siddharth Ramani
Siddharth Ramani

Reputation: 684

Hope This will help

$fruits = array("banana", "pineapple", array("apple", "mango"), "guava");

foreach ($fruits as $key => $value)
{
   echo count($value) . "<br />";
}

// Output : 1 1 2 1

Upvotes: 1

Don&#39;t Panic
Don&#39;t Panic

Reputation: 41810

If you only want to count the leaf nodes, you can take advantage of the fact that array_walk_recursive only touches those.

array_walk_recursive($fruits, function() use (&$count) { $count++; });
echo $count;  // 5

Upvotes: 0

ferc
ferc

Reputation: 558

If you expected it to return 5, it's because the array on the 3rd position is counted as an element. If you expected it to return 4, count's second argument specifies whether it should count recursively or not.

Upvotes: 0

Related Questions