Heim > Fragen und Antworten > Hauptteil
P粉5641921312023-08-29 09:28:59
foreach($equipxml as $equip) { $current_device = $equip->xpath("name"); if ( $current_device[0] == $device ) { // found a match in the file $nodeid = $equip->id; break; } }
只需使用break
。这样就可以了。
P粉7294365372023-08-29 00:47:33
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 "!";
结果输出: