简体   繁体   English

如何退出条件循环?

[英]How to exit a loop on condition?

$arr = array(1, 2, 3, 4);
foreach ($arr as $value) {
    $i=0;
    if($i==1||$i==2){continue;}
    echo $value;
    $i++;
}

I am a newbie of PHP, now i do a test, and i want to go out the loop not output 2 and 3, why the above code doesn't work? 我是PHP的新手,现在我要进行测试,并且想退出循环而不输出2和3,为什么上面的代码不起作用?

That's because you set $i = 0; 那是因为你设置$i = 0; on each iteration (Hence your check for $i==1||$i==2 will never match). 在每次迭代中(因此,对$i==1||$i==2将永远不匹配)。 Variable initialization go outside the loop: 变量初始化超出循环范围:

$arr = array(1, 2, 3, 4);
$i   = 0;
foreach ($arr as $value) {
    if ($i == 1 || $i == 2) {
        continue;
    }
    echo $value;
    $i++;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM