本文介绍了foreach的奇怪行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我认为这是一个正常的程序,但这是我得到的输出:
数组([0] =>一种[1] =>乙[2] =>C[3] =>C)
有人可以向我解释一下吗?
解决方案
这是有据可查的 PHP 行为请参阅php.net foreach 页面上的警告>
警告
即使在 foreach 循环之后,对 $value 和最后一个数组元素的引用仍然存在.建议用unset()销毁.
$a = array('a', 'b', 'c', 'd');foreach ($a as &$v) { }未设置($ v);foreach ($a as $v) { }打印_r($a);
编辑
尝试逐步指导这里实际发生的事情
$a = array('a', 'b', 'c', 'd');foreach ($a as &$v) { }//第一次迭代 $v 是对 $a[0] ('a') 的引用foreach ($a as &$v) { }//第二次迭代 $v 是对 $a[1] ('b') 的引用foreach ($a as &$v) { }//第三次迭代 $v 是对 $a[2] ('c') 的引用foreach ($a as &$v) { }//第 4 次迭代 $v 是对 $a[3] ('d') 的引用//在foreach循环结束时,//$v 仍然是对 $a[3] ('d') 的引用foreach ($a as $v) { }//第一次迭代 $v(仍然是对 $a[3] 的引用)//设置为 $a[0] ('a') 的值.//因为它是对 $a[3] 的引用,//它将 $a[3] 设置为 'a'.foreach ($a as $v) { }//第二次迭代 $v(仍然是对 $a[3] 的引用)//设置为 $a[1] ('b') 的值.//因为它是对 $a[3] 的引用,//它将 $a[3] 设置为 'b'.foreach ($a as $v) { }//第三次迭代 $v(仍然是对 $a[3] 的引用)//设置为 $a[2] ('c') 的值.//因为它是对 $a[3] 的引用,//它将 $a[3] 设置为 'c'.foreach ($a as $v) { }//第 4 次迭代 $v(仍然是对 $a[3] 的引用)//被设置为 $a[3] ('c' 因为//最后一次迭代).//因为它是对 $a[3] 的引用,//它将 $a[3] 设置为 'c'.
<?php
$a = array('a', 'b', 'c', 'd');
foreach ($a as &$v) { }
foreach ($a as $v) { }
print_r($a);
?>
I think it's a normal program but this is the output I am getting:
Array
(
[0] => a
[1] => b
[2] => c
[3] => c
)
Can someone please explain this to me?
解决方案
This is well-documented PHP behaviourSee the warning on the foreach page of php.net
$a = array('a', 'b', 'c', 'd');
foreach ($a as &$v) { }
unset($v);
foreach ($a as $v) { }
print_r($a);
EDIT
Attempt at a step-by-step guide to what is actually happening here
$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'.
这篇关于foreach的奇怪行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!