346

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>
    }
}
Pere
  • 1,647
  • 3
  • 27
  • 52
au_stan
  • 4,011
  • 2
  • 19
  • 24
  • for php not js. i can't assume they behave the same. – au_stan Feb 09 '12 at 17:26
  • 7
    gee - i've got to stop using jQuery so much. why did this get a downvote? +1, perfectly reasonable and well posed question. – mrtsherman Feb 09 '12 at 17:33
  • 13
    i only asked the question because (for whatever reason) i couldn't wrap my head around the php break doc and their examples. all good though. i'm not here to get badges and points, just fine answers. – au_stan Feb 10 '12 at 15:25

4 Answers4

751

if is not a loop structure, so you cannot "break out of it".

You can, however, break out of the foreach by simply calling break. In your example it has the desired effect:

$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 for completeness for others who stumble upon this question looking for an answer..

break takes an optional argument, which defines 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 "!";

Resulting output:

1 3 2 1 !

Kaii
  • 20,122
  • 3
  • 38
  • 60
  • 2
    Useful, thank you. Extra karma for mentioning the argument. The if-loop thing seems like a hack, though. Why not just wrap the rest of the statements in another if? I know you were just trying to be helpful, but note to the newbies. – Dan Barron Aug 05 '15 at 13:51
  • 3
    For those of you landing here but searching how to break out of a loop that contains an include statement use return instead of continue. – Nick Constantine Apr 12 '18 at 15:46
  • What if its a switch statement? Switch statements also use breaks. Would somebody simply put two breaks inside the switch e.g { case "break": echo 'break the switch and the loop'; break;break; } ? – Jevon Dec 05 '19 at 15:27
  • @Jevon no you would also simply write `switch($a) { case 'x': switch($b) { case 'x': break 2; }; break; }` the inner `break 2` leaves both switch statements. – Kaii Dec 05 '19 at 17:47
17
foreach($equipxml as $equip) {
    $current_device = $equip->xpath("name");
    if ( $current_device[0] == $device ) {
        // found a match in the file            
        $nodeid = $equip->id;
        break;
    }
}

Simply use break. That will do it.

Decent Dabbler
  • 22,532
  • 8
  • 74
  • 106
  • so then the break is breaking from the foreach and not the if. i think my confusion was from this statement `if ($abort_if_block) break;` i had originally set `break 2` and it failed. thanks – au_stan Feb 09 '12 at 17:25
  • 2
    Watch out for the break construct. If you forget the ; after it, it might get the result of next expression and start behaving unexpectedly (IE jumping out of much more than you would have wanted). I know everyone suggests against the use of GOTO, but I think that, for all those cases when you can't really do better than using a break, a goto can be a better option. Of course, for forward jumping (not too far either) only and without abuse! ;-) – maraspin Feb 09 '12 at 17:37
3

A safer way to approach breaking a foreach or while loop in PHP is to nest an incrementing counter variable and if conditional inside of the original loop. This gives you tighter control than break; which can cause havoc elsewhere on a complicated page.

Example:

// Setup a counter
$ImageCounter = 0;

// Increment through repeater fields
while ( condition ):
  $ImageCounter++;

   // Only print the first while instance
   if ($ImageCounter == 1) {
    echo 'It worked just once';
   }

// Close while statement
endwhile;
serraosays
  • 7,163
  • 3
  • 35
  • 60
1

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.

<?php

for ($i=0; $i < 100; $i++) { 
    if (i%2 == 0) {
        include(do_this_for_even.php);
    }
    else {
        include(do_this_for_odd.php);
    }
}

?>

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

Nick Constantine
  • 963
  • 9
  • 19