Reputation: 31
$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
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
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
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
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