我在 PHP 中使用数组,我对 unset() 函数感到困惑,这是代码:
<?php
$array = array(1, 2, 3, 4);
foreach ($array as $value) {
$value + 10;
}
unset($value);
print_r($array);
?>
是否有必要取消设置($value),当 $value 在 foreach 循环后仍然存在时,这是一个好习惯吗?
最佳答案
我知道这篇文章很旧,但我认为这个信息非常重要:
你问:
Is it necessary to unset($value), when $value remains after foreach loop, is it good practice?
这取决于你是否迭代按值 或 引用 .
第一种情况(按值(value)):
$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]
我希望这对将来的某人有用。 :)
关于php - 为什么我需要在 foreach 循环后取消设置 $value,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47128069/