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 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 !