Break out out forloop but within switch statement php

Lizard picture Lizard · Jul 16, 2010 · Viewed 10.8k times · Source

When I normally want to break out of a foreach loop before all of the iterations have completed I simply use a break; statement. e.g.

foreach($nodelist as $node) {
   if($metCriteria) {
       break;
   }
}

But my next example has a switch statement in it. And if one of the conditions are met then I need to break from the foreach loop. (The problem being the break is used for the switch statement)

foreach($nodelist as $node)
{
    switch($node->nodeName) {
        case "a" :
            //do something
            break;
        case "b" :
            //break out of forloop
            break;
    }
}

Do I simply set a variable in the switch statement then break after it? e.g.

$breakout = false;
foreach($nodelist as $node)
{
    switch($node->nodeName) {
        case "a" :
            //do something
            break;
        case "b" :
            $breakout = true;
            break;
    }
    if($breakout === true) break;
}

Is this the best solution? or this there another way?

Answer

Jonathan Kuhn picture Jonathan Kuhn · Jul 16, 2010

from the manual (break)

break accepts an optional numeric argument which tells it how many nested enclosing structures are to be broken out of.