While loop execution model in PHP - Time & Space Complexity
We want to understand how the time a while loop takes changes as the input grows.
How many times does the loop run when the input gets bigger?
Analyze the time complexity of the following code snippet.
$count = 0;
while ($count < $n) {
echo $count . "\n";
$count++;
}
This code prints numbers from 0 up to one less than n using a while loop.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The while loop runs repeatedly.
- How many times: It runs once for each number from 0 to n-1, so n times.
As n grows, the loop runs more times, directly matching n.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 times |
| 100 | About 100 times |
| 1000 | About 1000 times |
Pattern observation: The number of operations grows evenly as n grows.
Time Complexity: O(n)
This means the time it takes grows in a straight line with the size of n.
[X] Wrong: "The while loop runs only once no matter the input size."
[OK] Correct: The loop runs as many times as the condition allows, so it depends on n, not just once.
Understanding how loops grow with input size helps you explain your code clearly and shows you know how programs behave as data grows.
"What if we changed the loop to increase count by 2 each time? How would the time complexity change?"