0

I have this PHP code:

$a=array(1, 2, 3);
var_dump(current($a));
each($a);
each($a);
each($a);
var_dump(current($a));
$b=$a;
var_dump(current($a));

The output is "int(1) bool(false) int(1)" but I expect "int(1) bool(false) bool(false)", because after three times each the internal pointer of $a should be after the end of the array and stay there.

But apparently the assignment $b=$a sets the pointer of $a back to the first element again. What is going on here?

(If I remove one each, the output is "int(1) int(3) int(3)" as expected.)

1
  • your question is bit unclear. sorry may be i am unable, but still can you put your expected outcome in a bit nicer way? Commented Feb 6, 2016 at 23:41

3 Answers 3

2

From http://php.net/manual/en/function.each.php:

Caution: Because assigning an array to another variable resets the original array's pointer, our example above would cause an endless loop had we assigned $fruit to another variable inside the loop.

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

7 Comments

Why does the assignment not reset the pointer if there are only two each instead of three?
That's a good question, and I guess the answer is in the question :) I guess it only resets when it got to the end. Open a bug-report to php so they fix clarify it in the documentation...
In PHP7 this does what you'd expect (return 1, false, false) according to sandbox.onlinephpfunctions.com.... In 5.6 it seems it doesn't...
Right... sounds like this was some sort of side effect which got fixed in PHP 7. Thank you both.
Well "fixed" is probably depending on point of view, I would say "changed the undocumented behavior", which of course will break some working code for people when upgrading php :)
|
1

It's by design. This PHP manual page states:

Caution Because assigning an array to another variable resets the original array's pointer, our example above would cause an endless loop had we assigned $fruit to another variable inside the loop.

Comments

1

This behavior is corrected in PHP 7.

$a=array(1, 2, 3);
var_dump(current($a)); // 1
each($a);
each($a);
each($a);
var_dump(current($a)); // false
$b=$a;
var_dump(current($a)); // php7-> false; php5.6 -> 1 

The changes described on php wiki page.

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.