Break statement with levels in PHP - Time & Space Complexity
Let's see how using a break statement with levels affects how long a PHP program runs.
We want to know how the number of steps changes as the input grows.
Analyze the time complexity of the following code snippet.
for ($i = 0; $i < $n; $i++) {
for ($j = 0; $j < $m; $j++) {
if ($j == 2) {
break 2; // exit both loops
}
// some constant time operation
}
}
This code loops over two levels but breaks out of both loops early when $j reaches 2.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The inner loop runs but breaks early at $j == 2.
- How many times: The outer loop runs only once ($i = 0), and the inner loop runs 3 times (j=0,1,2) before
break 2exits both loops.
Because of the break 2, both loops exit after just a few operations, regardless of input size.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 3 steps |
| 100 | About 3 steps |
| 1000 | About 3 steps |
Pattern observation: The work is constant because the loops terminate early, independent of $n.
Time Complexity: O(1)
This means the program's running time stays constant as $n increases, thanks to the multilevel break stopping both loops early.
[X] Wrong: "Because there are two loops, the time must be O(n*m)."
[OK] Correct: The break 2 exits both loops after $j reaches 2 in the first outer iteration, so total work is constant, not O(n*m).
Understanding how break with levels changes loop behavior helps you explain code efficiency clearly and confidently in interviews.
What if the break statement was removed? How would the time complexity change?