Lizard
Lizard

Reputation: 45002

Break out out forloop but within switch statement php

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?

Upvotes: 42

Views: 14454

Answers (4)

Abdul Manan
Abdul Manan

Reputation: 2375

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

Upvotes: 21

Latze
Latze

Reputation: 1871

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

Upvotes: -2

Jonathan Kuhn
Jonathan Kuhn

Reputation: 15301

from the manual (break)

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

Upvotes: 75

Viper_Sb
Viper_Sb

Reputation: 1817

break 2;

break x will break out of that many levels

Upvotes: 13

Related Questions