tags:

views:

72

answers:

3

I have this code:

$a = array ('zero','one','two', 'three');

foreach ($a as &$v) {

}

foreach ($a as $v) {
  echo $v.PHP_EOL;
}

Can somebody explain why the output is: zero one two two .

From zend certification study guide.

+3  A: 

Because on the second loop, v is still a reference to the last array item, so it's overwritten each time.

You can see it like that:

$a = array ('zero','one','two', 'three');

foreach ($a as &$v) {

}

foreach ($a as $v) {
  echo $v.'-'.$a[3].PHP_EOL;
}

As you can see, the last array item takes the current loop value: 'zero', 'one', 'two', and then it's just 'two'... : )

Macmade
ok, this means that in the last iteration the last item or remains two or it is assigned two again, why not three why it stops at last-1? :)
Centurion
It does not stop. The last array item is assigned with the current loop value. So it's assigned 'zero', then 'one', then 'two'. On the last iteration, it's assigned with its very own value, which is 'two', because of the previous iteration. So it simply remains 'two'.
Macmade
Thank for explanation!
Centurion
+2  A: 

I'm not sure I can explain why but this is documented in the manual.

The comment also provides some solutions if that is what you are looking for.

Rupert
+2  A: 

Because if you create a reference to a variable, all names for that variable (including the original) BECOME REFERENCES.

dejavu
Rupert
dejavu