0
0
PHPprogramming~10 mins

Break statement with levels in PHP - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Break statement with levels
Start Outer Loop i=1
Start Inner Loop j=1
Check Condition
Yes
Break with level 2
Exit Inner and Outer Loops
Continue after loops
The break statement with a level exits multiple nested loops at once, skipping remaining iterations.
Execution Sample
PHP
<?php
for ($i = 1; $i <= 3; $i++) {
    for ($j = 1; $j <= 3; $j++) {
        if ($j == 2) break 2;
        echo "$i,$j\n";
    }
}
?>
This code prints pairs of i and j until j equals 2, then breaks out of both loops.
Execution Table
StepijCondition (j==2)ActionOutput
111FalsePrint '1,1'1,1
212TrueBreak 2 levels (exit both loops)
3---Loops exited
💡 Break 2 levels triggered at j=2, exiting both inner and outer loops.
Variable Tracker
VariableStartAfter 1After 2Final
i11--
j12--
Key Moments - 2 Insights
Why does the break statement exit both loops instead of just the inner one?
Because the break uses a level of 2, it tells PHP to exit two nested loops at once, as shown in execution_table step 2.
What happens to the variables after the break 2 statement?
Both loops stop immediately, so variables i and j do not update further, as seen in variable_tracker final values.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the output at step 1?
A"1,1"
B"1,2"
CNo output
D"2,1"
💡 Hint
Check the Output column in execution_table row 1.
At which step does the break 2 statement cause the loops to exit?
AStep 1
BStep 2
CStep 3
DNever
💡 Hint
Look at the Action column in execution_table row 2.
If the break statement was just 'break;' without a level, what would happen?
AOnly the inner loop would exit
BBoth loops would exit
CNo loops would exit
DThe program would error
💡 Hint
Recall that break without a level exits only the current loop.
Concept Snapshot
break n;
- Exits n nested loops immediately.
- Default n=1 exits only current loop.
- Useful to stop multiple loops at once.
- Syntax: break 2; exits two loops.
- Stops further iterations after break.
Full Transcript
This example shows how the break statement with a level works in PHP. The code has two loops: outer loop with variable i and inner loop with variable j. When j equals 2, the break 2 statement runs. This causes both the inner and outer loops to stop immediately. The execution table shows step by step: first printing '1,1', then at j=2 breaking out of both loops. The variable tracker shows i and j values before the break. Key moments clarify why break 2 exits both loops and what happens to variables. The quiz tests understanding of output, break timing, and difference from break without level. The snapshot summarizes the syntax and behavior of break with levels.