<?PHP
$a = [1,2,3];
foreach($a as &$val) {
$val = $val + 1;
}
foreach($a as $val) {
$val = $val - 1;
}
var_dump($a);
// output 2,3,1
?>
我输出2,3,1作为最终数组而不是2,3,4我无法理解PHP是如何解释这段代码的,有谁能帮我理解事情是怎么回事?
解决方法:
您需要在第一个foreach()中的引用上调用unset()以获得预期的行为:
$a = [1, 2, 3];
foreach($a as &$val)
{
$val = $val + 1;
}
unset($val);
// $a = [2, 3, 4];
请参阅documentation中的注释:
Reference of a
$value
and the last array element remain even after the
foreach loop. It is recommended to destroy it byunset()
.