1

what's the magic? the last element of $data changed, after 2 for each loop.

<?php
$data = array("1" => "a", "2" => "b");
print_r($data);
foreach($data as $k=>&$v) {}
foreach($data as $k=>$v) {}
print_r($data);

output:[2] => a after the second foreach

Array
(
    [1] => a
    [2] => b
)
Array
(
    [1] => a
    [2] => a
)

it the code change to this,the array won't change:

<?php
foreach($data as $k=>&$v) {}
foreach($data as $k=>&$v) {}
AbraCadaver
  • 78,200
  • 7
  • 66
  • 87
islq
  • 86
  • 10
  • 2
    Because `&v`. Reference of `$v` and the last array element remain even after the foreach loop. It is recommended to destroy it by `unset()`. – AbraCadaver May 14 '15 at 01:37
  • i can't understand,why the reference changed the original array? i do nothing with that reference – islq May 14 '15 at 02:02

1 Answers1

6

From the foreach manual:

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

So at the end of the first foreach, $v is a reference to the last element in the array. The next foreach's first iteration changes the value of $v (to the value of the first array element) which is a reference to the last element in the array, so it is changed.

$data = array("1" => "a", "2" => "b");
print_r($data);
foreach($data as $k=>&$v) {}
unset($v);                     // *** UNSET HERE ***
foreach($data as $k=>$v) {}
print_r($data);

Result:

Array
(
    [1] => a
    [2] => b
)
Array
(
    [1] => a
    [2] => b
)
AbraCadaver
  • 78,200
  • 7
  • 66
  • 87