Can you 'exit' a loop in PHP?

PhpLoops

Php Problem Overview


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?

Php Solutions


Solution 1 - Php

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";
}

Solution 2 - Php

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

Solution 3 - Php

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.

Solution 4 - Php

You can use the break keyword.

Solution 5 - Php

$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";
}

Solution 6 - Php

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionalexView Question on Stackoverflow
Solution 1 - PhpTheTXIView Answer on Stackoverflow
Solution 2 - PhpWilliam HolroydView Answer on Stackoverflow
Solution 3 - PhpHansView Answer on Stackoverflow
Solution 4 - PhpGabriel SosaView Answer on Stackoverflow
Solution 5 - PhpPiseth SokView Answer on Stackoverflow
Solution 6 - PhpPatrick MichaelsenView Answer on Stackoverflow