Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 360
Lizard Avatar asked Jul 16 '10 16:07

Lizard


People also ask

Does Break break out of a switch statement?

You can use the break statement to end processing of a particular labeled statement within the switch statement. It branches to the end of the switch statement. Without break , the program continues to the next labeled statement, executing the statements until a break or the end of the statement is reached.

How do you break out of a while loop in PHP?

Using break keyword: The break keyword is used to immediately terminate the loop and the program control resumes at the next statement following the loop. To terminate the control from any loop we need to use break keyword.


1 Answers

from the manual (break)

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

like image 160
Jonathan Kuhn Avatar answered Sep 22 '22 08:09

Jonathan Kuhn