问题描述
我有一个foreach循环和一个if语句。如果找到一场比赛,我需要最终摆脱这个问题。 foreach($ equipxml as $ equip){
$ current_device = $ equip-> xpath(name );
if($ current_device [0] == $ device){
//找到文件中的匹配
$ nodeid = $ equip-> id;
<突破了if和foreach这里>
$ / code $ / pre
解决方案 code>如果
不是一个循环结构,所以你不能突破它。
您可以通过简单地调用。在你的例子中,它具有所需的效果:
$ forex $ equipxml as $ equip
$ current_device = $ equip->的xpath( 名称);
if($ current_device [0] == $ device){
//找到文件中的匹配
$ nodeid = $ equip-> id;
//将离开foreach循环,if语句
break;
}
this_command_is_not_executed_after_a_match_is_found();
$ b $ p $为了完整性绊倒这个问题寻找答案。
接受一个可选的参数,它定义了它应该中断多少个循环结构。例子:
foreach(array('1','2','3')as $ a){
回显$ a;
foreach(array('3','2','1')为$ b){
echo$ b;
if($ a == $ b){
break 2; //这将破坏两个foreach循环
}
}
echo。; //永远不会达到
}
echo!;
结果输出:
If - for some obscure reason - you want to break
out of an if
statement (which is not a loop structure and thus not breakable per definition), you can simply wrap your if
in a tiny loop structure so you can jump out of that code block.
Please note that this is a total hack and normally you would not want to do this:
do if ($foo)
{
// Do something first...
// Shall we continue with this block, or exit now?
if ($abort === true) break;
// Continue doing something...
} while (false);
The example above is taken from a comment in the PHP docs
If you wonder about the syntax: It works because an abbreviated syntax is used here. The outer curly braces can be left out because the loop structure contains only a single statement: if ($foo) { .. }
.
Another example for this:do $i++; while ($i < 100)
is equivalent to do { $i++; } while ($i < 100)
.
这篇关于如果和foreach分离的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!