Continue statement with levels in PHP - Time & Space Complexity
Let's see how using the continue statement with levels affects how many times parts of the code run.
We want to know how skipping certain loops changes the total work done.
Analyze the time complexity of the following code snippet.
for ($i = 0; $i < $n; $i++) {
for ($j = 0; $j < $n; $j++) {
if ($j % 2 == 0) {
continue 2; // skips to next $i iteration
}
// some constant time operation
}
}
This code loops over two levels. When $j is even, it skips the rest of inner and outer loop body and moves to the next $i.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Nested loops over $i and $j.
- How many times: Outer loop runs $n times; inner loop runs partially due to continue 2.
Because continue 2 skips inner and outer loop when $j is even, inner loop does very little work per outer loop.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 5 (one inner iteration per outer loop when $j is odd) |
| 100 | 50 |
| 1000 | 500 |
Pattern observation: Operations grow roughly linearly with input size, not squared.
Time Complexity: O(n)
This means the total work grows in direct proportion to the input size.
[X] Wrong: "Since there are two loops, the time must be O(n²)."
[OK] Correct: The continue 2 skips many inner loop steps, so the inner loop does not fully run each time.
Understanding how control statements like continue with levels affect loops helps you explain code efficiency clearly and confidently.
"What if we changed continue 2 to continue 1? How would the time complexity change?"