Php foreach的奇怪行为
有人能给我解释一下吗?这是一个有很好文档记录的PHP行为 请参见php.net的foreach页面上的 警告 即使在foreach循环之后,$值和最后一个数组元素的引用仍然保留。建议通过unset()将其销毁 编辑 尝试一步一步地指导这里实际发生的事情Php foreach的奇怪行为,php,arrays,foreach,Php,Arrays,Foreach,有人能给我解释一下吗?这是一个有很好文档记录的PHP行为 请参见php.net的foreach页面上的 警告 即使在foreach循环之后,$值和最后一个数组元素的引用仍然保留。建议通过unset()将其销毁 编辑 尝试一步一步地指导这里实际发生的事情 $a = array('a', 'b', 'c', 'd'); foreach ($a as &$v) { } unset($v); foreach ($a as $v) { } print_r($a); 第一 正如我们所期望的那样
$a = array('a', 'b', 'c', 'd');
foreach ($a as &$v) { }
unset($v);
foreach ($a as $v) { }
print_r($a);
第一
正如我们所期望的那样,foreach循环不会对数组进行任何更改。
但是,它确实会导致为$v
的每个$a
元素分配一个引用,
因此,在第一个循环结束时,$v
实际上是对$a[2]
的引用
一旦第二个循环开始,$v
现在被分配每个循环的值
要素但是,$v
已经是对$a[2]的引用代码>因此,任何值
分配给它的元素将自动复制到数组的最后一个元素中
因此,在第一次迭代期间,$a[2]
将变为零,然后变为一,然后变为零
再一次,被有效地复制到自己身上。为了解决这个问题,你
应始终取消设置引用中使用的变量
循环,或者更好的是,完全避免使用前者。什么是“我认为,这是正常的程序,但我看到了网络……”然后……啊,这是什么意思?@Bart Kiers:他似乎在发呆。这可能是对这种行为的最好解释:可能是@Manish Trivedi的重复:请参阅警告部分,了解发生这种情况的原因。你的程序没有问题。解释得很好!谢谢:D我必须记住,其中一个作为参考/重复,所有关于foreach参考的其他答案都没有你在这里解释的那么好!在您的unset($v)中
,为什么在foreachs范围之外可以访问$v
:o@nawfal-我不明白这个问题。。。。PHP局部变量范围在函数中,而不仅仅是在loop@MarkBaker非常感谢。你回答了我的问题。刚刚接触到PHP特性:)
Array
(
[0] => a
[1] => b
[2] => c
[3] => c
)
$a = array('a', 'b', 'c', 'd');
foreach ($a as &$v) { }
unset($v);
foreach ($a as $v) { }
print_r($a);
$a = array('a', 'b', 'c', 'd');
foreach ($a as &$v) { } // 1st iteration $v is a reference to $a[0] ('a')
foreach ($a as &$v) { } // 2nd iteration $v is a reference to $a[1] ('b')
foreach ($a as &$v) { } // 3rd iteration $v is a reference to $a[2] ('c')
foreach ($a as &$v) { } // 4th iteration $v is a reference to $a[3] ('d')
// At the end of the foreach loop,
// $v is still a reference to $a[3] ('d')
foreach ($a as $v) { } // 1st iteration $v (still a reference to $a[3])
// is set to a value of $a[0] ('a').
// Because it is a reference to $a[3],
// it sets $a[3] to 'a'.
foreach ($a as $v) { } // 2nd iteration $v (still a reference to $a[3])
// is set to a value of $a[1] ('b').
// Because it is a reference to $a[3],
// it sets $a[3] to 'b'.
foreach ($a as $v) { } // 3rd iteration $v (still a reference to $a[3])
// is set to a value of $a[2] ('c').
// Because it is a reference to $a[3],
// it sets $a[3] to 'c'.
foreach ($a as $v) { } // 4th iteration $v (still a reference to $a[3])
// is set to a value of $a[3] ('c' since
// the last iteration).
// Because it is a reference to $a[3],
// it sets $a[3] to 'c'.