40

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?

Lizard
  • 43,732
  • 39
  • 106
  • 167

4 Answers4

73

from the manual (break)

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

Jonathan Kuhn
  • 15,279
  • 3
  • 32
  • 43
  • 2
    +1 This was exactly what I needed. Bonus points for using a built in language construct - I was doing it @Lizard style up until now. – Ed Orsi Feb 05 '13 at 17:49
  • 1
    5.4.0 Removed the ability to pass in variables (e.g., $num = 2; break $num;) as the numerical argument. – Average Joe Jan 07 '17 at 06:26
19

The accepted Answer has no practical example let me share with you.

break 2 

means exit from both loop and switch.

$i = 0;
while (++$i) {
    switch ($i) {
    case 5:
        echo "At 5<br />\n";
        break 1;  /* Exit only the switch. */
    case 10:
        echo "At 10; quitting<br />\n";
        break 2;  /* Exit the switch and the while. */
    default:
        break;
    }
}
Abdul Manan
  • 2,255
  • 3
  • 27
  • 51
12

break 2;

break x will break out of that many levels

Viper_Sb
  • 1,809
  • 14
  • 18
-2

Just use the {'s - it will keep the code from "running". Much better than the break-statement if you ask me.

Latze
  • 1,843
  • 7
  • 22
  • 29