if
不是一个循环 struct ,所以你不能"跳出它".
然而,你只需拨打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
接受一个可选参数,该参数定义了它应该中断的how many个循环 struct .例子:
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 !