132

I have a loop that is doing some error checking in my PHP code. Originally it looked something like this...

foreach($results as $result) {
    if (!$condition) {
        $halt = true;
        ErrorHandler::addErrorToStack('Unexpected result.');
    }

    doSomething();
 }

if (!$halt) {
    // do what I want cos I know there was no error
}

This works all well and good, but it is still looping through despite after one error it needn't. Is there a way to escape the loop?

alex
  • 479,566
  • 201
  • 878
  • 984

6 Answers6

225

You are looking for the break statement.

$arr = array('one', 'two', 'three', 'four', 'stop', 'five');
while (list(, $val) = each($arr)) {
    if ($val == 'stop') {
        break;    /* You could also write 'break 1;' here. */
    }
    echo "$val<br />\n";
}
TheTXI
  • 37,429
  • 10
  • 86
  • 110
  • 13
    @Gabriel, it answers the question, the code sample is exactly that, a sample. You may just as well complain about the non-descriptive "$arr" array name. – paxdiablo Feb 26 '09 at 02:51
  • 5
    @Gabriel: I am posting code directly referenced in the PHP manual, and it accurately shows the usage of the break statement. – TheTXI Feb 26 '09 at 02:52
  • @Pax, for me thats subjective, each time I put an example I tried to put a real world code. – Gabriel Sosa Feb 26 '09 at 02:53
  • 1
    @Gabriel: You didn't post an example at all, and the link you gave goes to the exact same source I supplied (which is where the sample code comes from at the very top). You basically did the same thing as I did, but made it so the OP won't see the sample until after he clicks the link. – TheTXI Feb 26 '09 at 02:58
  • 4
    That *is* a weird way to loop however! – alex Aug 10 '10 at 00:06
  • I had continue; in my loop but it kept going to next ones, whereas I just wanted to stop the whole for() loop. Thank you. – jeffkee Nov 01 '16 at 21:26
165

As stated in other posts, you can use the break keyword. One thing that was hinted at but not explained is that the keyword can take a numeric value to tell PHP how many levels to break from.

For example, if you have three foreach loops nested in each other trying to find a piece of information, you could do 'break 3' to get out of all three nested loops. This will work for the 'for', 'foreach', 'while', 'do-while', or 'switch' structures.

$person = "Rasmus Lerdorf";
$found = false;

foreach($organization as $oKey=>$department)
{
   foreach($department as $dKey=>$group)
   {
      foreach($group as $gKey=>$employee)
      {
         if ($employee['fullname'] == $person)
         {
            $found = true;
            break 3;
         }
      } // group
   } // department
} // organization
William Holroyd
  • 3,344
  • 1
  • 21
  • 25
  • 5
    Good point. It is explained pretty clearly in the PHP manual near the top. I don't think this was imperative for this particular question, but this is still very good to know. +1 – TheTXI Feb 26 '09 at 03:05
53

break; leaves your loop.

continue; skips any code for the remainder of that loop and goes on to the next loop, so long as the condition is still true.

alex
  • 479,566
  • 201
  • 878
  • 984
Hans
  • 1,292
  • 9
  • 7
8

You can use the break keyword.

S.S. Anne
  • 15,171
  • 8
  • 38
  • 76
Gabriel Sosa
  • 7,897
  • 4
  • 38
  • 48
4
$arr = array('one', 'two', 'three', 'four', 'stop', 'five');
foreach ($arr as $val) {
    if ($val == 'stop') {
        break;    /* You could also write 'break 1;' here. */
    }
    echo "$val<br />\n";
}
Piseth Sok
  • 1,789
  • 1
  • 20
  • 24
4

All of these are good answers, but I would like to suggest one more that I feel is a better code standard. You may choose to use a flag in the loop condition that indicates whether or not to continue looping and avoid using break all together.

$arr = array('one', 'two', 'three', 'four', 'stop', 'five');
$length = count($arr);
$found = false;
for ($i = 0; $i < $length && !$found; $i++) {
    $val = $arr[$i];
    if ($val == 'stop') {
        $found = true; // this will cause the code to 
                       // stop looping the next time 
                       // the condition is checked
    }
    echo "$val<br />\n";
}

I consider this to be better code practice because it does not rely on the scope that break is used. Rather, you define a variable that indicates whether or not to break a specific loop. This is useful when you have many loops that may or may not be nested or sequential.