我知道这篇文章很旧,但我认为这个信息非常重要:
你问:
是否需要取消设置($value),当 $value 在 foreach 之后仍然存在时
循环,这是一种好习惯吗?
这取决于您是按值还是按引用进行迭代。
第一种情况(按值):
$array = array(1, 2, 3, 4);
foreach ($array as $value) {
//here $value is 1, then 2, then 3, then 4
}
//here $value will continue having a value of 4
//but if you change it, nothing happens with your array
$value = 'boom!';
//your array doesn't change.
所以没有必要取消设置 $value
第二种情况(通过引用):
$array = array(1, 2, 3, 4);
foreach ($array as &$value) {
//here $value is not a number, but a REFERENCE.
//that means, it will NOT be 1, then 2, then 3, then 4
//$value will be $array[0], then $array[1], etc
}
//here $value it's not 4, it's $array[3], it will remain as a reference
//so, if you change $value, $array[3] will change
$value = 'boom!'; //this will do: $array[3] = 'boom';
print_r ($array); //Array ( [0] => 1 [1] => 2 [2] => 3 [3] => boom! )
所以在这种情况下这是一个很好的做法取消设置 $value,因为这样做会破坏对数组的引用。 有必要吗?没有,但如果你不这样做,你应该非常小心。
它可能会导致像这样的意外结果:
$letters = array('a', 'b', 'c', 'd');
foreach ($letters as &$item) {}
foreach ($letters as $item) {}
print_r ($letters); //output: Array ( [0] => a [1] => b [2] => c [3] => c )
// [a,b,c,c], not [a,b,c,d]
这也适用于 PHP 7.0
未设置的相同代码:
$letters = array('a', 'b', 'c', 'd');
foreach ($letters as &$item) {}
unset ($item);
foreach ($letters as $item) {}
print_r ($letters); //output: Array ( [0] => a [1] => b [2] => c [3] => d )
// now it's [a,b,c,d]
我希望这对将来的某人有用。 :)