Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
314 views
in Technique[技术] by (71.8m points)

php 5.3 - Why does PHP overwrite values when I iterate through this array twice (by reference, by value)

If I iterate through an array twice, once by reference and then by value, PHP will overwrite the last value in the array if I use the same variable name for each loop. This is best illustrated through an example:

$array = range(1,5);
foreach($array as &$element)
{
  $element *= 2;
}
print_r($array);
foreach($array as $element) { }
print_r($array);

Output:

Array ( [0] => 2 [1] => 4 [2] => 6 [3] => 8 [4] => 10 )

Array ( [0] => 2 [1] => 4 [2] => 6 [3] => 8 [4] => 8 )

Note that I am not looking for a fix, I am looking to understand why this is happening. Also note that it does not happen if the variable names in each loop are not each called $element, so I'm guessing it has to do with $element still being in scope and a reference after the end of the first loop.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

After the first loop $element is still a reference to the last element/value of $array.
You can see that when you use var_dump() instead of print_r()

array(5) {
  [0]=>
  int(2)
...
  [4]=>
  &int(2)
}

Note that & in &int(2).
With the second loop you assign values to $element. And since it's still a reference the value in the array is changed, too. Try it with

foreach($array as $element)
{
  var_dump($array);
}

as the second loop and you'll see.
So it's more or less the same as

$array = range(1,5);
$element = &$array[4];
$element = $array[3];
// and $element = $array[4];
echo $array[4];

(only with loops and multiplication ...hey, I said "more or less" ;-))


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...