可能意外发生的引用和数组

Nic*_*ool 5 php arrays

有人可以在这里解释一下这个参考吗?我知道引用会导致它发生但是怎么样?为什么只是在2的指数?为什么不是其他的?

我知道什么是引用,但在这个特殊的例子中我丢失了:

$a = array ('zero','one','two');
foreach ($a as &$v) {
}
foreach ($a as $v) {
}
print_r ($a);
Run Code Online (Sandbox Code Playgroud)

输出:

Array ( [0] => zero [1] => one [2] => one )
Run Code Online (Sandbox Code Playgroud)

hek*_*mgl 4

在第一个foreach循环之后,$v将是对 中最后一个元素的引用$a

在下面的循环中$v,将分配给zerothenone和 then 本身(它是一个引用)。one由于先前的分配,它现在的值是现在的。one这就是为什么最后有两个 ' 的原因。

为了更好地理解:您的代码执行与以下行相同的操作:

// first loop
$v = &$a[0];
$v = &$a[1];
$v = &$a[2]; // now points to the last element in $a

// second loop ($v is a reference. The last element changes on every step of loop!)
$v = $a[0]; // since $v is a reference the last element has now the value of the first -> zero
$v = $a[1]; // since $v is a reference the last element has now the value of the second last -> one
$v = $a[2]; // this just assigns one = one
Run Code Online (Sandbox Code Playgroud)