我有一个 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>
}
}
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 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!
foreach
或
while
循环的更安全方法是在原始循环内部嵌套一个递增计数器变量和 if
条件。这为您提供了比 break;
更严格的控制,这可能会在复杂页面的其他地方造成严重破坏。示例:
// Setup a counter
$ImageCounter = 0;
// Increment through repeater fields
while ( condition ):
$ImageCounter++;
// Only print the first while instance
if ($ImageCounter == 1) {
echo 'It worked just once';
}
// Close while statement
endwhile;