Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
243 views
in Technique[技术] by (71.8m points)

Can you 'exit' a loop in PHP?

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?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...