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 "!";
結果輸出: