且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

当我两次遍历此数组两次时,PHP为什么会覆盖值(按引用,按值)

更新时间:2023-02-05 20:05:56

在第一个循环之后,$ 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" ;-))