“break” from the switch, then “continue” in the loop

Is it possible to exit the switch and then continue in a loop?

For example:

$numbers= array(1,2,3,4,5,6,7,8,9,0); $letters = array('a', 'b', 'c', 'd', 'e', 'f', 'g'); foreach($letters as $letter) { foreach($numbers as $number) { switch($letter) { case 'd': // So here I want to 'break;' out of the switch, 'break;' out of the // $numbers loop, and then 'continue;' in the $letters loop. break; } } // Stuff that should be done if the 'letter' is not 'd'. } 

Can this be done, and what will be the syntax?

+7
source share
3 answers

Do you want to use break n

 break 2; 

After finding out, it looks like you want to continue 2;

+13
source

Instead of break use continue 2 .

+7
source

I know this is a serious necro, but ... since I came here from Google, I decided that I would leave other confusion.

If he meant to break out of the switch and just finished the number cycle, then break 2; would be okay. continue 2; will just continue the cycle of the number and will continue to repeat it, to be continue 'd each time.

Ergo, the correct answer should be continue 3; .

The transition to commentary in documents continues to go mainly to the end of the structure, for switching it (it will feel the same as a gap), for the cycles that he would have typed in the next iteration.

See: http://codepad.viper-7.com/dGPpeZ

An example in the case above n / a:

 <?php echo "Hello, World!<pre>"; $numbers= array(1,2,3,4,5,6,7,8,9,0); $letters = array('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i'); $i = 0; foreach($letters as $letter) { ++$i; echo $letter . PHP_EOL; foreach($numbers as $number) { ++$i; switch($letter) { case 'd': // So here I want to 'break;' out of the switch, 'break;' out of the // $numbers loop, and then 'continue;' in the $letters loop. continue 3; // go to the end of this switch, numbers loop iteration, letters loop iteration break; case 'f': continue 2; // skip to the end of the switch control AND the current iteration of the number loop, but still process the letter loop break; case 'h': // would be more appropriate to break the number loop break 2; } // Still in the number loop echo " $number "; } // Stuff that should be done if the 'letter' is not 'd'. echo " $i " . PHP_EOL; } 

Results:

 Hello, World! a 1 2 3 4 5 6 7 8 9 0 11 b 1 2 3 4 5 6 7 8 9 0 22 c 1 2 3 4 5 6 7 8 9 0 33 d e 1 2 3 4 5 6 7 8 9 0 46 f 57 g 1 2 3 4 5 6 7 8 9 0 68 h 70 i 1 2 3 4 5 6 7 8 9 0 81 

continue 2; not only processes the letter loop for the letter d, but even processes the rest of the loop (note that $i incremented and printed after f). (What may or may not be desirable ...)

Hope this helps someone else who brings you here first.

+4
source

All Articles