Challenge - 5 Problems
Break Mastery in PHP
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of nested loops with break 2
What is the output of this PHP code using
break 2 inside nested loops?PHP
<?php for ($i = 1; $i <= 3; $i++) { for ($j = 1; $j <= 3; $j++) { if ($j == 2) { break 2; } echo "$i$j "; } } ?>
Attempts:
2 left
💡 Hint
Remember that
break 2 exits two levels of loops immediately.✗ Incorrect
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.
❓ Predict Output
intermediate2:00remaining
Effect of break 1 in nested loops
What will be the output of this PHP code using
break 1 inside nested loops?PHP
<?php for ($i = 1; $i <= 2; $i++) { for ($j = 1; $j <= 3; $j++) { if ($j == 2) { break 1; } echo "$i$j "; } } ?>
Attempts:
2 left
💡 Hint
break 1 only exits the innermost loop.✗ Incorrect
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 '.
🔧 Debug
advanced2:00remaining
Identify error with break level
What error will this PHP code produce when using
break 3 inside two nested loops?PHP
<?php for ($i = 0; $i < 2; $i++) { for ($j = 0; $j < 2; $j++) { if ($j == 1) { break 3; } echo "$i$j "; } } ?>
Attempts:
2 left
💡 Hint
Check how many nested loops exist and the break level used.
✗ Incorrect
The code tries to break 3 levels but only 2 loops exist. PHP throws a fatal error: 'Cannot break 3 levels'.
❓ Predict Output
advanced2:00remaining
Output with break in switch inside loops
What is the output of this PHP code with
break 2 inside a switch within nested loops?PHP
<?php for ($i = 1; $i <= 3; $i++) { for ($j = 1; $j <= 3; $j++) { switch ($j) { case 2: break 2; default: echo "$i$j "; } } } ?>
Attempts:
2 left
💡 Hint
Remember
break 2 exits two control structures, here loops and switch.✗ Incorrect
The break 2 inside the switch exits both the switch and the outer for loop. So only '11 ' prints before exiting all loops.
🧠 Conceptual
expert3:00remaining
Understanding break levels in complex nested structures
Consider this PHP code with three nested loops and a
break 2 inside the innermost loop. After the break executes, which loops continue running?PHP
<?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 "; } } } ?>
Attempts:
2 left
💡 Hint
Break level counts how many nested loops to exit starting from innermost.
✗ Incorrect
break 2 exits the innermost and the middle loops. The outermost loop continues its next iteration.