Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.2k views
in Technique[技术] by (71.8m points)

PHP foreach使用不当导致的死循环问题

有如下PHP的代码:

$list = [1, 2, 3];
// $v1 是引用
foreach ($list as &$v1) {
    foreach ($list as $v2) {
        echo 'loop';
    }
}

运行后一切是正常的,两次遍历后,一共输出9次loop结束程序。
但是如果在第二次遍历中,修改$list中任意元素的值:

$list = [1, 2, 3];
// $v1 是引用
foreach ($list as &$v1) {
    foreach ($list as $v2) {
        // 修改任意位置的值,不一定是0
        $list[0] = 1;
        echo 'loop';
    }
}

这段代码就会进行死循环,调试发现在死循环的情况下外面一层的foreach的key始终是0。为什么会这样呢?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

foreach 和 引用 使用不正确导致的,使用完了要销毁.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...