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
 //switch value wasn't handled

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

Mirth Integration: Iterate through specific HL7 segments

Many of us in the healthcare integration community use the Mirth Integration Engine for HL7 and other integration needs.

In the past I’ve been active on the Mirth Community Forums as Bostad,  both asking and answering questions.  I haven’t been that active lately as my duties don’t leave me much time.

I do sometime receive direct requests,  and it was one of those that prompted me to start posting some of my Mirth programming tips here.

If you’re curious about healthcare integration and/or HL7 messaging, you can read about it here.

When required to iterate through repeating segments of an HL7 message,  here’s my method:

var i = 0;   //iteration variable
for each (seg in msg..ROL) {   //iterates through each ROL segment of an incoming HL7 message


if (seg['ROL.3']['ROL.3.1'].toString() != 'FAMILY DOCTOR')  {

   channelMap.put('ROL ' + i,'Not Family Doc');


In the code above,  you’ll note that the variable seg holds the current iteration of the target segment.

You’ll also note that the code above doesn’t do anything useful…I don’t want to flood you with a bunch of lines of code that aren’t helpful.

To reference specific fields within the segment,  unlike when referencing msg or tmp objects,  you do not use the initial segment name as an index!

//referencing msg and tmp

var strM = msg['ROL']['ROL.3']['ROL.3.1'].toString();
var strT = tmp['ROL']['ROL.3]['ROL.3.1'].toString();

//referencing seg (from within implied loop)

var strS = seg['ROL.3]['ROL.3.1']..toString();

If anything is unclear,  or you have further questions, feel free to ask in comments.

PHP: Function to display array contents with optional exit

Our hospital recently implemented the iPeople Echo Data Repository,  allowing us to pull data from our Meditech Hospital Information System,  into a SQL Server data base where we can access it like normal people,  instead of relying on Meditech’s internal report writing language (NPR) to spit out text based reports.

This has allowed me to do things that were previously next to impossible,  such as providing near real-time patient census data.

I will publish some entries on this,  even though they are industry specific,  but that’s not what I’m here to do today.

Because of how the data is stored,  and the complexity of some of the requests I get,  I usually end up storing information in associative arrays within my PHP script.

Many of these arrays are built programmatically.

As I test things,  I often need to check the structure and contents of these arrays.

Naturally,  I would plug in the following code:


echo '<pre>';  //this is html tag for 'pretty print'.  It displays output in a readable format


echo '</pre>';

exit;  //  I usually threw in an exit as some of the scripts could take a while to run,  and they all spit out formatted XML


On a recent high stress, short deadline project,  I was faced with data that made no sense at all.  I needed to associate data from several tables from Meditech’s payroll module,  but there wasn’t any clear association at the level I needed.

As I was constantly trying new queries in PHP,  I was tired of typing the code above,  so finally I created a function called “showarray()”.

Here’s the syntax:

showarray($array,[exit = true]);

So, instead of typing all that,  I type one line of code,  and if I don’t want it to exit when done,  I put false as a second parameter.

Here’s the function:

function showarray($out,$exit = true) {
echo '<pre>';


echo '</pre>';

if ($exit == true) {




It really helped speed things along…

PHP: Find index of specific value in nested array

Array recursion is a bit of a bear to tackle for any programmer.

While working on an HL7 parser,  I needed to be able to determine where in the HL7 message a certain string was located.   As I parsed the HL7 message into an array,  I needed to do a recursive search.

There are many solutions out there,  but when I first tried to tackle this,  the ones that I found that worked,  would either only tell me if a value existed in a nested array, but not what the index was,  or would only give me the root index.

After much trial and error,  I finally came up with a solution that is elegant and will return the location index, regardless if its associative or numeric.

The key to recursion is writing a function that can call itself.

The logic I use is to iterate through an array using foreach,   check  if the current value is an array,   if so,  call the recursion function and concatenate the value returned (if any).

This gives me a bar delimited string,  showing me exactly where in the nested array my search string exists.

Here is my function:


function recurse($input,$string) {

if (!is_array($input)) {

return 'Input parameter must be an array!';


$out = ''; //As I'm returning a delimited string, I need to declare the output string

foreach($input as $key=>$val) {

if (is_array($val)) {

$r = recurse($val,$string);

if (strlen($r) > 0) { //checking the length prevents you from getting a return for every index

$out .= $key.'|'.$r; //I chose bar delimited, you can change this to whatever, or even use an array


} else {

if ($val == $string) {

$out .= $key;



return $out;


While I wrote this for HL7 parsing, I’ve created a script with some generic arrays to demonstrate

$sarr = array(



$narr = array(

 'FIVE' => 5,
 'SIX' => 6,
 'SEVEN' => 7,
 'TOYS' => $sarr


$test = array (

 'ONE' => 1,
 'TWO' => 2,
 'THREE' => 3,
 'FOUR' => $narr,


echo '<pre>';
echo '<br>';
echo '<br>';

and here’s the output!





Finding the Console Window

Sending debugging and tracing info to the console is a fantastic way to reduce time debugging and tweaking code.

You’ll see it mentioned in almost every thread answering a programming question ever.

However, there are many coders who have difficulty finding where the console window is.

For web pages,  most browsers have debugging tools which can be accessed by hitting the F12 key.  You will see several tabs,  but one of them should be labelled Console.

In .NET,  its really tricky.

In VS2012 at least,  you need to go to the Application tab of the “Properties” page for your project.

You’ll see ‘Output Type’,  and a drop down.  Select ‘Console Application’, and every time you run you’re app,  the console window will appear.

But please, for the love of all that is holy…..remember to switch it back to ‘Windows Application’ for your release build!

JQuery Quick Tip: Loop through each visible object


I need to loop through some checkboxes identified by a class.

There are lots of “try this” in the forums, so I wanted to post what worked in jquery 1.11.1

This iterates through objects of a class selector that are visible and concatenates their ID to a string.

….because I wanted the example to be simple,  that’s why.


$('.aacheck').filter(':visible').each(function(i,o) {    //i: iteration  o: object

chdept += '~' + $(o).attr('id');


If you need to check multiple conditions (like checkboxes that are visible AND checked)…

$('.aacheck').filter(':visible').filter(':checked').each(function(i,o) {    //i: iteration  o: object

chdept += '~' + $(o).attr('id');



PHP: Tracking session variable content while developing

I like using session variables to track various and sundry as users navigate through my sites.

The problem comes when I forget to change, or load a session variable.

What I used to do was add var_dump($_SESSION) lines to my scripts…but of course, then you have to go remove them.

This weekend I thought of a cleaner way.

I create a whole new file, usually sessvar.php. I then point my browser to it, and whenever I need to see what the session variables are, I simply refresh the page.

So, you’d navigate to yourpageurl/sessvar.php in a tab besides what ever you’re using to check your work, and refresh the sessvar.php page whenever you needed to see what variables your stored were.