PHP: BREAK and CONTINUE from Nested Routines (Such as loops and switch statements)

One of the most frequent “gotchas” that I run into are breaking out of loops properly.

Its one of those things that I don’t really think about when I’m banging out code,  and that I can miss when I go back to see why things aren’t working.

I’m currently working on a project that requires me to parse through comments entered into our Meditech Hospital Information System,  looking for key phrases and performing certain actions based on these key phrases.

The issue is that the comments are a single string (meaning that users may enter several things into the same field (its a Meditech thing),  and that this is free text.

I won’t bore you with the details, but suffice it to say, “Yay Reg Ex!” 🙂

The routine I’m working on looks to see if the user entered a month if a particular code (EDD) has been entered into the field.

That was easy enough,  but what I found that some users would enter a numeric month day,  or day month.

So I did a preg_match to find that.   I found that the script would hit this every time,  even though I placed it where it should only run if the month string wasn’t found.

I quickly realized that the break statement I placed to break out of the month search loop was only breaking out of the case statement!  So when it went looking for the next month,  it wouldn’t find it and as such would run the digit match routine!

The way to handle this is really easy…both the break and continue statements in PHP have optional integer arguments where you can specify how many structures to break out of!

Don’t worry,  I’m not going to paste in my whole solution and let you find the interesting bits.  You can always contact me if you’d like more detail on the project I describe.

In this example I’ll show you how to use continue from loops and nested loops.
You can use the same logic for breaks.


foreach($results as $row) {

 if ($row['text'] == 'EDD') {
 
 continue; //this will skip to the next $results;
 
 }

 foreach($pattern as $check) {
 
 if ($check['action'] == 'edd') {
 
 //do something here
 continue; // continue to the next $pattern
 
 } else {
 
 if ($something == $thathing) {
 
 continue 2; // continue to the next $results
 
 } else {
 
 break 2; //breaks out of $results
 
 }
 }
 
 
 }

}

In this example I’ll show you how to break out of a switch case statement

foreach($results as $row) {
 
 switch($row['text']) {
 
 case 'edd':
 
 if ($datacheck == 'yes') { //something indicating that you're finished processing $results
 
 //some code here
 
 break 2; //breaks out of both switch and $results
 
 
 } else {
 
 
 continue; //jumps to next $results
 
 }
 
 
 break; // case break
 
 default:
 
 //switch value wasn't handled
 break;
 
 
 }
 
 
}

Hopefully you found this useful. Please feel free to ask questions or suggest improvements in the comments section!