2

Sorry i it is duplicated, but I don't seem to find the exact scenario I need to clarify.

So my question is why this:

var = array ();
echo count (var);

prints 0.

and this:

var = array (array());
echo count (var);

prints 1?

Thanks!

1
  • 1
    Because there is a nested array Commented Nov 28, 2014 at 16:11

4 Answers 4

5

Because you've put an array into an array. Even if that inner array is empty, it's still SOMETHING.

It's like putting an empty plastic bag into another plastic bag. That outer bag now contains one item: another plastic bag.

Sign up to request clarification or add additional context in comments.

Comments

1

In the first case, you create an empty array.

$var = array();

The contents of this array may look like this:

[ ]

There is nothing here. So, count($var) is zero.

But if you create a nested array, you would have

$var = array(array());

The contents of $var would now be something like this:

[ [] ]

The inner array doesn't have anything inside it. But, the outer array has an empty array inside it. And therefore, its count is 1.

Further explanation:

Consider an array to be a plastic box.

In the first case, you have nothing inside the box, and so the count is 0.

In the second case, however, you have an empty box inside the box. So, count is 1.

2 Comments

man thanks for the further details! I accepted the first answer to be fair with the timings, but all the answers are good! Thank to you all people. Its nice to be programming alone knowing that this community exists :)
No problems. MarcB's answer is simpler and better :) And happy coding, @AlbertoPadilla!
1

it is because there exist one value in the array and it does not matter whether the inner array is empty or not.

On index 0 an empty array exists which implies array is not blank so count results 1.

Comments

-1

when you do this var = array (array()); you have two dimensional array. if you familiar java, it seems like

Object var[][] = {
   {},
};

so, var.length is ", but var[0].length is 0

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.