phpforeach中的foreach($arras&$value),&的作用与区别
当 foreach 开始执行时,数组内部的指针会自动指向第一个单元。这意味着不需要在 foreach 循环之前调用reset()。
由于 foreach 依赖内部数组指针,在循环中修改其值将可能导致意外的行为。
可以很容易地通过在 $value 之前加上 & 来修改数组的元素。此方法将以引用赋值而不是拷贝一个值。
<?php$arr = array("1","2","3","4","5","6","7","8","9");
foreach($arr as $key => &$val)
{
$val = $val * 2;
}
print_r($arr);
输出: Array ( [0] => 2 [1] => 4 [2] => 6 [3] => 8 [4] => 10 [5] => 12 [6] => 14 [7] => 16 [8] => 18 )
如果$val没有&符号
$arr = array("1","2","3","4","5","6","7","8","9");foreach($arr as $key => $val)
{
$val = $val * 2;
}
print_r($arr);
输出: Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 [5] => 6 [6] => 7 [7] => 8 [8] => 9
以上是 phpforeach中的foreach($arras&$value),&的作用与区别 的全部内容, 来源链接: utcz.com/z/515508.html