我有一个 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>
}
}
最佳答案
if
不是循环结构,所以你不能“跳出它”。
但是,您可以通过简单地调用 break
来跳出 foreach
。 .在您的示例中,它具有预期的效果:
$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 immediately and also the if statement
break;
some_function(); // never reached!
}
another_function(); // not executed after match/break
}
只是为了其他偶然发现这个问题并寻找答案的人的完整性..
break
接受一个可选参数,它定义了它应该中断的多少个循环结构。示例:
foreach (['1','2','3'] as $a) {
echo "$a ";
foreach (['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 !
关于php - 突破 if 和 foreach,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9215588/