0
0
PHPprogramming~5 mins

For loop execution model in PHP - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: For loop execution model
O(n)
Understanding Time Complexity

We want to understand how the time a for loop takes changes as we increase the number of times it runs.

How does the work inside the loop grow when the loop runs more times?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


for ($i = 0; $i < $n; $i++) {
    echo $i . "\n";
}
    

This code prints numbers from 0 up to one less than $n. It runs the loop $n times.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The echo statement inside the for loop.
  • How many times: Exactly $n times, once for each loop cycle.
How Execution Grows With Input

As $n grows, the number of times the loop runs grows the same way.

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

Pattern observation: The work grows directly with the input size. Double the input, double the work.

Final Time Complexity

Time Complexity: O(n)

This means the time it takes grows in a straight line with the number of loop runs.

Common Mistake

[X] Wrong: "The loop runs faster because it just prints numbers."

[OK] Correct: Printing still happens every time the loop runs, so the time grows with the number of loops, not faster.

Interview Connect

Understanding how loops grow with input size helps you explain code efficiency clearly and confidently in interviews.

Self-Check

"What if we added a nested for loop inside this loop? How would the time complexity change?"