For loop execution model in PHP - Time & Space Complexity
We want to understand how the time a for loop takes changes as we increase the number of times it runs.
How does the work inside the loop grow when the loop runs more times?
Analyze the time complexity of the following code snippet.
for ($i = 0; $i < $n; $i++) {
echo $i . "\n";
}
This code prints numbers from 0 up to one less than $n. It runs the loop $n times.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The
echostatement inside the for loop. - How many times: Exactly
$ntimes, once for each loop cycle.
As $n grows, the number of times the loop runs grows the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 times |
| 100 | 100 times |
| 1000 | 1000 times |
Pattern observation: The work grows directly with the input size. Double the input, double the work.
Time Complexity: O(n)
This means the time it takes grows in a straight line with the number of loop runs.
[X] Wrong: "The loop runs faster because it just prints numbers."
[OK] Correct: Printing still happens every time the loop runs, so the time grows with the number of loops, not faster.
Understanding how loops grow with input size helps you explain code efficiency clearly and confidently in interviews.
"What if we added a nested for loop inside this loop? How would the time complexity change?"