I have a foreach loop and an if statement. If a match is found i need to ultimately break out of the foreach.
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>
}
}
if
is not a loop structure, so you cannot "break out of it".You can, however, break out of the
foreach
by simply callingbreak
. In your example it has the desired effect:Just for completeness for others that stumble upon this question looking for an answer..
break
takes an optional argument, which defines how many loop structures it should break. Example:Resulting output:
If - for some obscure reason - you want to
break
out of anif
statement (which is not a loop structure and thus not breakable per definition), you can simply wrap yourif
in a tiny loop structure so you can jump out of that code block.Please note that this is a total hack and normally you would not want to do this:
The example above is taken from a comment in the PHP docs
If you wonder about the syntax: It works because an abbreviated syntax is used here. The outer curly braces can be left out because the loop structure contains only a single statement:
if ($foo) { .. }
.Another example for this:
do $i++; while ($i < 100)
is equivalent todo { $i++; } while ($i < 100)
.Simply use
break
. That will do it.A safer way to approach breaking a
foreach
orwhile
loop in PHP is to nest an incrementing counter variable andif
conditional inside of the original loop. This gives you tighter control thanbreak;
which can cause havoc elsewhere on a complicated page.Example:
For those of you landing here but searching how to break out of a loop that contains an include statement use return instead of break or continue.
If you want to break when being inside do_this_for_even.php you need to use return. Using break or continue will return this error: Cannot break/continue 1 level. I found more details here