Can you 'exit' a loop in PHP?

alex picture alex · Feb 26, 2009 · Viewed 267.5k times · Source

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?

Answer

TheTXI picture TheTXI · Feb 26, 2009

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