0
0
PHPprogramming~5 mins

Echo statement in PHP - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Echo statement
O(n)
Understanding Time 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.

Scenario Under Consideration

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 Repeating Operations

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 $n times.
How Execution Grows With Input

Each time we increase $n, the echo runs more times, adding more work.

Input Size (n)Approx. Operations
1010 echoes
100100 echoes
10001000 echoes

Pattern observation: The work grows directly with the number of times we want to print.

Final Time Complexity

Time Complexity: O(n)

This means if you double the number of prints, the time to run roughly doubles too.

Common Mistake

[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.

Interview Connect

Understanding how simple repeated actions add up helps you explain how programs handle bigger tasks step by step.

Self-Check

"What if we replaced the echo inside the loop with a function call that also prints? How would the time complexity change?"