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?

Don't Panic
41.9k11 gold badges70 silver badges87 bronze badges
asked Apr 25, 2018 at 16:25
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
answered Apr 25, 2018 at 16:30
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
answered Apr 25, 2018 at 17:20

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.

answered Apr 25, 2018 at 16:30

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
answered Apr 25, 2018 at 16:44

Comments

0

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

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

Emilio Gort
3,4553 gold badges32 silver badges44 bronze badges
answered Apr 25, 2018 at 16:31

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.