Breaking if and foreach
P粉651109397
2023-08-28 11:32:39
<p>I have a foreach loop and an if statement. I need to finally break out of the foreach if a match is found. </p>
<pre class="brush:php;toolbar:false;">foreach ($equipxml as $equip) {
$current_device = $equip->xpath("name");
if ($current_device[0] == $device) {
// Found a match in the file.
$nodeid = $equip->id;
<break out of if and foreach here>
}
}</pre>
<p><br /></p>
Just use
break
. that's it.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
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:Result output: