本文介绍了当我两次遍历此数组两次时,PHP为什么会覆盖值(按引用,按值)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我两次遍历一个数组,一次通过引用然后再一次通过值,如果我为每个循环使用相同的变量名,PHP将覆盖数组中的最后一个值.最好通过一个例子来说明:

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);

输出:

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

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

请注意,我不是要寻求修复,而是要了解为什么会发生这种情况.另请注意,如果每个循环中的变量名称未分别称为$element,则不会发生这种情况,因此我猜测这与$element仍在作用域内以及第一个循环结束后的引用有关.

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.

推荐答案

在第一个循环之后,$ element仍然是对$ array的最后一个元素/值的引用.
您会看到,当您使用var_dump()而不是print_r()

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)
}

请注意&在&int(2)中.
在第二个循环中,您将值分配给$ element.并且由于它仍然是一个引用,因此数组中的值也被更改了.尝试

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" ;-))

这篇关于当我两次遍历此数组两次时,PHP为什么会覆盖值(按引用,按值)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-26 11:38