我有一个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>
}
}
如果不是一个循环结构,那么你就不能“跳出来”。
但是,您可以通过简单地调用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 "!";
输出结果:
One, three, two, one!