问题描述
if
不是循环结构,所以你不能“打破它”。
但是,您可以foreach
通过简单地调用break
. 在您的示例中,它具有预期的效果:
$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
}
只是为了其他偶然发现这个问题并寻找答案的人的完整性。
break
接受一个可选参数,它定义了它应该中断 多少个循环结构。 例子:
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 !
解决方法
我有一个 foreach 循环和一个 if 语句。如果找到匹配项,我需要最终摆脱 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>
}
}