2

I'm not sure how to word it.

Take the following example.

<?
$arr = array('first','second','third', 'fourth');
foreach ($arr as $k=>&$n) {
    $n = $n;
}
var_dump($arr);
>?

returns

array(4) {
  [0]=>
  string(5) "first"
  [1]=>
  string(6) "second"
  [2]=>
  string(5) "third"
  [3]=>
  &string(6) "fourth"
}

That makes total sense, why would anything change? Well, adding a second loop that doesn't even do anything is where I got lost.

<?
$arr = array('first','second','third', 'fourth');
foreach ($arr as $k=>&$n) {
    $n = $n;
}
foreach ($arr as $k=>$n) {
;
}
var_dump($arr);
?>

returns

array(4) {
  [0]=>
  string(5) "first"
  [1]=>
  string(6) "second"
  [2]=>
  string(5) "third"
  [3]=>
  &string(5) "third"
}

The last value of the array has become the same as the second to last. Why?

  • http://stackoverflow.com/questions/4969243/strange-behavior-of-foreach/4969286#4969286 – Mark Baker Mar 19 '14 at 14:39
  • 2
    [Here is a nice description of exactly this effect](http://schlueters.de/blog/archives/141-References-and-foreach.html) and why it happens with reference iteration. – Digital Chris Mar 19 '14 at 14:46

3 Answers3

6

You're turning $n into a reference:

foreach ($arr as $k=>&$n) {
                     ^----

Once a PHP variable is "referenced" like that, it STAYS a reference, so in your next loop:

foreach ($arr as $k=>$n) {

That $n will still be a reference to the LAST item you iterated over in the first loop.

Marc B
  • 356,200
  • 43
  • 426
  • 500
1

You got the address operator & before $n in the first loop. Removing that will solve the problem.

This problem is explained here:

Why php iteration by reference returns a duplicate last record?

Community
  • 1
  • 1
thatidiotguy
  • 8,701
  • 13
  • 60
  • 105
0

A stab in the dark but maybe try resetting the internal pointer of the array using reset() ?

http://www.php.net/reset

<?
$arr = array('first','second','third', 'fourth');
foreach ($arr as $k=>&$n) {
    $n = $n;
}

reset($arr);
foreach ($arr as $k=>$n) {
;
}

var_dump($arr);
?>
Dean Whitehouse
  • 884
  • 1
  • 8
  • 25