突破 if 和 foreach [英] break out of if and foreach
本文介绍了突破 if 和 foreach的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个 foreach 循环和一个 if 语句.如果找到匹配项,我需要最终退出 foreach.
I have a foreach loop and an if statement. If a match is found i need to ultimately break out of the foreach.
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>
}
}
推荐答案
if
不是循环结构,所以你不能打破它".
if
is not a loop structure, so you cannot "break out of it".
然而,您可以通过简单地调用 break 来突破
.在您的示例中,它具有预期的效果:foreach
You can, however, break out of the foreach
by simply calling break
. In your example it has the desired effect:
$device = "wanted";
foreach($equipxml as $equip) {
$current_device = $equip->xpath("name");
if ( $current_device[0] == $device ) {
// found a match in the file
$nodeid = $equip->id;
// will leave the foreach loop and also the if statement
break;
some_function(); // never reached!
}
another_function(); // not executed after match/break
}
只是为了其他人偶然发现这个问题以寻求答案的完整性..
Just for completeness for others that stumble upon this question looking for an answer..
break
接受一个可选参数,它定义了有多少 应该打破的循环结构.示例:
break
takes an optional argument, which defines how many loop structures it should break. Example:
foreach (array('1','2','3') as $a) {
echo "$a ";
foreach (array('3','2','1') as $b) {
echo "$b ";
if ($a == $b) {
break 2; // this will break both foreach loops
}
}
echo ". "; // never reached!
}
echo "!";
结果输出:
1 3 2 1 !
这篇关于突破 if 和 foreach的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文