0
0
PHPprogramming~5 mins

Print statement in PHP - Time & Space Complexity

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

Scenario Under Consideration

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

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

Each time we increase $n, the print runs that many more times.

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

Pattern observation: The number of print operations grows directly with the input size.

Final Time Complexity

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.

Common Mistake

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

Interview Connect

Understanding how simple loops affect time helps you explain how programs scale, a key skill in coding interviews and real projects.

Self-Check

"What if we replaced the print statement with a nested loop that also prints? How would the time complexity change?"