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; } }
Just use break
. that's it.
P粉7294365372023-08-29 00:47:33
if
is not a loop structure, so you can't "break it".
However, you can break out of foreach
break. In your example it has the expected effect: by simply calling
$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 }
Just to keep it intact for anyone else who stumbles across this question and is looking for an answer.
break
Takes optional arguments defining how many loop structures it should break. Example:
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 "!";
Result output: