栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

foreach的奇怪行为

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

foreach的奇怪行为

这是有据可查的PHP行为,请参阅php.net的foreach页面上的警告。

警告

即使在 foreach 循环之后,仍保留 $ value的 引用和最后一个数组元素。建议通过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) { }   // 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'.


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/408453.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号