Print statement in PHP - Time & Space Complexity
Let's see how the time to run a simple print statement changes as we run it multiple times.
We want to know how the number of print commands affects the total work done.
Analyze the time complexity of the following code snippet.
<?php
for ($i = 0; $i < $n; $i++) {
print("Hello\n");
}
?>
This code prints "Hello" a number of times equal to the input size $n.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The print statement inside the loop.
- How many times: It runs once for each number from 0 up to
$n - 1, so$ntimes.
Each time we increase $n, the print runs that many more times.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 prints |
| 100 | 100 prints |
| 1000 | 1000 prints |
Pattern observation: The number of print operations grows directly with the input size.
Time Complexity: O(n)
This means if you double the input size, the print commands double too, so the work grows in a straight line with input.
[X] Wrong: "The print statement takes the same time no matter how many times it runs."
[OK] Correct: Each print command takes some time, so more prints mean more total time. The total work grows with the number of prints.
Understanding how simple loops affect time helps you explain how programs scale, a key skill in coding interviews and real projects.
"What if we replaced the print statement with a nested loop that also prints? How would the time complexity change?"