0

Possible Duplicate:
Strange behavior Of foreach
Strange behaviour after loop by reference - Is this a PHP bug?

I do have a problem with Foreach, I can't understand the second foreach.

why the third part of $foo array has 'two' in its value!

In as much as we know, if we remove the '&'(in first foreach) the problem will solve, but why?

<?php

$foo = array('one', 'two', 'three');

foreach ($foo as &$bar)
{
// no-op
}

var_dump($foo);

foreach ($foo as $bar)
{
 // no-op
}

var_dump($foo);
?>
###############################################

produces:

 array(3) {
   [0]=>string(3) "one"
   [1]=>string(3) "two"
   [2]=>&string(5) "three"
  }
   array(3) {
  [0]=>string(3) "one"
  [1]=>string(3) "two"
  [2]=>&string(3) "two"
  } 
Community
  • 1
  • 1
Mehdi Raash
  • 8,721
  • 2
  • 29
  • 42
  • 3
    That second foreach is basically: `foreach ($foo as $foo[2])`. So each iteration, you are updating the last element of $foo with the current element. And since the last element is lost, you ultimately end up with the second-to-last in the last position. – Matthew Jul 25 '12 at 19:18

2 Answers2

2

From the docs:

Reference of a $value and the last array element remain even after the foreach loop. It is recommended to destroy it by unset().

So in your case:

<?php

$foo = array('one', 'two', 'three');

foreach ($foo as &$bar)
{
    // no-op
}

var_dump($foo);

unset($bar);

foreach ($foo as $bar)
{
 // no-op
}

var_dump($foo);
?>
PeeHaa
  • 71,436
  • 58
  • 190
  • 262
0

In the first foreach you're using a reference with '&' symbol, so the values are actually modified. I don't know what it inside of first foreach but you're overwriting old values, that's why in your second foreach values are not the same as in the beginning.

Edit There's a neat answer in this post, or just use unset as recommended

Community
  • 1
  • 1
Jorge Zapata
  • 2,316
  • 1
  • 30
  • 57
  • 1
    Have you tried running the code in the question? It produces that output, and there's no (obvious) over-writing going on, just the two foreach loops. – andrewsi Jul 25 '12 at 19:19