Echo statement in PHP - Time & Space Complexity
Let's see how the time it takes to run a simple echo statement changes as we run it more times.
We want to know how the work grows when we print more messages.
Analyze the time complexity of the following code snippet.
for ($i = 0; $i < $n; $i++) {
echo "Hello, world!\n";
}
This code prints "Hello, world!" a number of times based on the input size $n.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The echo 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 echo runs more times, adding more work.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 echoes |
| 100 | 100 echoes |
| 1000 | 1000 echoes |
Pattern observation: The work grows directly with the number of times we want to print.
Time Complexity: O(n)
This means if you double the number of prints, the time to run roughly doubles too.
[X] Wrong: "Echo statements run instantly and don't add to time as we print more."
[OK] Correct: Each echo takes some time, so printing more times adds up and takes longer.
Understanding how simple repeated actions add up helps you explain how programs handle bigger tasks step by step.
"What if we replaced the echo inside the loop with a function call that also prints? How would the time complexity change?"