break 2 inside nested loops?<?php for ($i = 1; $i <= 3; $i++) { for ($j = 1; $j <= 3; $j++) { if ($j == 2) { break 2; } echo "$i$j "; } } ?>
break 2 exits two levels of loops immediately.The break 2 statement exits both the inner and outer loops as soon as $j == 2. So only the first iteration 11 is printed before breaking out.
break 1 inside nested loops?<?php for ($i = 1; $i <= 2; $i++) { for ($j = 1; $j <= 3; $j++) { if ($j == 2) { break 1; } echo "$i$j "; } } ?>
break 1 only exits the innermost loop.The break 1 exits only the inner loop when $j == 2. So for each outer loop iteration, only $j == 1 prints. Output is '11 21 '.
break 3 inside two nested loops?<?php for ($i = 0; $i < 2; $i++) { for ($j = 0; $j < 2; $j++) { if ($j == 1) { break 3; } echo "$i$j "; } } ?>
The code tries to break 3 levels but only 2 loops exist. PHP throws a fatal error: 'Cannot break 3 levels'.
break 2 inside a switch within nested loops?<?php for ($i = 1; $i <= 3; $i++) { for ($j = 1; $j <= 3; $j++) { switch ($j) { case 2: break 2; default: echo "$i$j "; } } } ?>
break 2 exits two control structures, here loops and switch.The break 2 inside the switch exits both the switch and the outer for loop. So only '11 ' prints before exiting all loops.
break 2 inside the innermost loop. After the break executes, which loops continue running?<?php for ($a = 1; $a <= 2; $a++) { for ($b = 1; $b <= 2; $b++) { for ($c = 1; $c <= 2; $c++) { if ($c == 2) { break 2; } echo "$a$b$c "; } } } ?>
break 2 exits the innermost and the middle loops. The outermost loop continues its next iteration.
