3

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

ideone

code:

<?php
$arr = array(array(1),array(2),array(3));
foreach($arr as &$i) {
    print_r($i);
}
foreach($arr as $i) {
    print_r($i);
}

output

Array
(
    [0] => 1
)
Array
(
    [0] => 2
)
Array
(
    [0] => 3
)
Array
(
    [0] => 1
)
Array
(
    [0] => 2
)
Array
(
    [0] => 2
)

I know I just need to put an unset($i) after the first loop to fix it, but I can't really figure out what would cause the 2 to be repeated. It always seems to be the last value that is overwritten with the 2nd to last value. It doesn't seem to happen when the array items are primitives ('scalar' in PHP).

I've ran into this problem a few times with reused variables when someone forgets to unset a reference. Really confused me the first time.

Duplicates

Community
  • 1
  • 1
mpen
  • 272,448
  • 266
  • 850
  • 1,236
  • I answered almost exactly this question with a very detailed explanation just yesterday... http://stackoverflow.com/questions/8901861/understanding-foreach-logic-with-references-why-is-the-1st-element-being-chang/8901999#8901999 – Mark Baker Jan 18 '12 at 19:37
  • @MarkBaker: Your answer here was more clear: http://stackoverflow.com/a/4969286/65387 Thanks. – mpen Jan 18 '12 at 23:19
  • Hopefully, between the two sets of answers you'll have the answer to your question – Mark Baker Jan 18 '12 at 23:41
  • @MarkBaker: Yeah, I think I see what's going on now. Was just curious. Not fond of the scoping in PHP at all. – mpen Jan 19 '12 at 01:52

1 Answers1

1

This is happening because your second loop is modifying the value of $arr[2] with each iteration (because after the first loop finished, $i is left as a reference to $arr[2]). So, as the second loop runs it assigns each element of $arr in turn to $arr[2], then prints the result.

David O'Riva
  • 696
  • 3
  • 5