Bird
0
0

You want to stop processing nested loops early when a condition is met, but only exit the inner loop sometimes and both loops other times. Which code snippet correctly uses break with levels?

hard📝 Application Q15 of 15
PHP - Loops

You want to stop processing nested loops early when a condition is met, but only exit the inner loop sometimes and both loops other times. Which code snippet correctly uses break with levels?

for ($i = 0; $i < 5; $i++) {
    for ($j = 0; $j < 5; $j++) {
        if ($i == 2 && $j == 3) {
            break 2; // exit both loops
        } elseif ($j == 4) {
            break; // exit inner loop only
        }
        echo "$i,$j\n";
    }
}
ACorrect use of break with levels to control loop exit.
Bbreak 2; should be break 1; to exit both loops.
Cbreak; cannot be used inside nested loops.
Dbreak 2; exits only the inner loop.
Step-by-Step Solution
Solution:
  1. Step 1: Understand break with levels usage

    break 2; exits two loops, break; exits only the current loop.
  2. Step 2: Analyze code logic

    When $i==2 && $j==3, both loops exit with break 2;. When $j==4, only inner loop exits with break;. This matches the requirement.
  3. Final Answer:

    Correct use of break with levels to control loop exit. -> Option A
  4. Quick Check:

    break n exits n loops, break exits current loop [OK]
Quick Trick: Use break n; for multiple loops, break; for single loop exit [OK]
Common Mistakes:
  • Confusing break 2; with break 1;
  • Thinking break; exits all loops
  • Misusing break levels causing logic errors

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PHP Quizzes