0
0
PHPprogramming~20 mins

Break statement with levels in PHP - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Break Mastery in PHP
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2: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 ";
    }
}
?>
A11
B11 12 13 21 22 23 31 32 33
C11 12
D12
Attempts:
2 left
💡 Hint
Remember that break 2 exits two levels of loops immediately.
Predict Output
intermediate
2: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 ";
    }
}
?>
A11 12 21 22
B11 21
C11 12 13 21 22 23
D11 21 22
Attempts:
2 left
💡 Hint
break 1 only exits the innermost loop.
🔧 Debug
advanced
2: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 ";
    }
}
?>
AFatal error: Cannot break 3 levels
BNo output, loops run fully
COutput: 0001
DSyntax error: unexpected break
Attempts:
2 left
💡 Hint
Check how many nested loops exist and the break level used.
Predict Output
advanced
2: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 ";
        }
    }
}
?>
A11 13 21 23 31 33
B11 12 13 21 22 23 31 32 33
C11
D12
Attempts:
2 left
💡 Hint
Remember break 2 exits two control structures, here loops and switch.
🧠 Conceptual
expert
3: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 ";
        }
    }
}
?>
AOnly the outermost loop continues; the two inner loops break
BOnly the innermost loop breaks; middle and outer loops continue
CAll three loops break and stop running
DThe innermost and middle loops break; outer loop continues
Attempts:
2 left
💡 Hint
Break level counts how many nested loops to exit starting from innermost.