2
$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?

4
  • 4 for the first level and 2 for second .. also the array is an elem .. Commented Apr 25, 2018 at 16:28
  • 4
    Upvote simply because this is the first time I've realized that count() can take a second parameter. Commented Apr 25, 2018 at 16:36
  • @MonkeyZeus same here! Although I think it would be more useful if the recursive count didn't include the inner arrays. Maybe I'm missing some value of that. Commented Apr 25, 2018 at 16:51
  • 1
    @Don'tPanic I was juggling that thought as well but I think stackoverflow.com/a/50027183/2191572 explains it nicely. Commented Apr 25, 2018 at 17:22

5 Answers 5

1
$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
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

0

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.

Comments

0

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

Comments

0

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.