打破 if 和 foreach
我有一个 foreach 循环和一个 if 语句。如果找到匹配项,我需要最终摆脱 foreach 和 if 。
foreach($equipxml as $equip) {
$current_device = $equip->xpath("name");
if ($current_device[0] == $device) {
// found a match in the file
$nodeid = $equip->id;
// <break out of if and foreach here>
}
}
I have a foreach loop and an if statement. If a match is found I need to ultimately break out of that foreach and if.
foreach($equipxml as $equip) {
$current_device = $equip->xpath("name");
if ($current_device[0] == $device) {
// found a match in the file
$nodeid = $equip->id;
// <break out of if and foreach here>
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
if
不是循环结构,因此您无法“打破它”。但是,您可以通过简单地调用
break
。在您的示例中,它具有预期的效果:
只是为了让其他偶然发现此问题并寻找答案的人完整。.
< code>break 接受一个可选参数,它定义它应该中断多少个循环结构。示例:
结果输出:
if
is not a loop structure, so you cannot "break out of it".You can, however, break out of the
foreach
by simply callingbreak
. In your example it has the desired effect:Just for completeness for others who stumble upon this question looking for an answer..
break
takes an optional argument, which defines how many loop structures it should break. Example:Resulting output:
只需使用
break
即可。这样就可以了。Simply use
break
. That will do it.打破 PHP 中的
foreach
或while
循环的更安全方法是在原始循环内嵌套递增计数器变量和if
条件。这为您提供了比break;
更严格的控制,这可能会在复杂页面的其他地方造成严重破坏。例子:
A safer way to approach breaking a
foreach
orwhile
loop in PHP is to nest an incrementing counter variable andif
conditional inside of the original loop. This gives you tighter control thanbreak;
which can cause havoc elsewhere on a complicated page.Example:
对于那些登陆此处但正在搜索如何跳出包含 include 语句的循环的人,请使用 return 而不是 Break 或 continue。
如果你想在 do_this_for_even.php 中中断,你需要使用 return。使用中断或继续将返回此错误:无法中断/继续 1 级。我在此处找到了更多详细信息
For those of you landing here but searching how to break out of a loop that contains an include statement use return instead of break or continue.
If you want to break when being inside do_this_for_even.php you need to use return. Using break or continue will return this error: Cannot break/continue 1 level. I found more details here