0
0
PHPprogramming~5 mins

PHP process model per request - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: PHP process model per request
O(n)
Understanding Time Complexity

When PHP handles a web request, it starts fresh each time. This means the work done depends on what the request asks for.

We want to see how the time PHP takes grows as the request does more work.

Scenario Under Consideration

Analyze the time complexity of the following PHP script handling a request.


<?php
// Simulate processing a list of items per request
$items = range(1, $n); // $n is input size
foreach ($items as $item) {
    // Process each item
    echo $item . "\n";
}
?>
    

This code processes each item in a list one by one for each request.

Identify Repeating Operations

Look for loops or repeated steps.

  • Primary operation: The foreach loop that goes through each item.
  • How many times: Exactly once for each item in the list, so $n times.
How Execution Grows With Input

As the number of items grows, the work grows too.

Input Size (n)Approx. Operations
1010 loops, 10 prints
100100 loops, 100 prints
10001000 loops, 1000 prints

Pattern observation: The work grows directly with the number of items. Double the items, double the work.

Final Time Complexity

Time Complexity: O(n)

This means the time PHP takes grows in a straight line with the number of items it processes.

Common Mistake

[X] Wrong: "PHP keeps data between requests, so processing time stays the same no matter the input size."

[OK] Correct: PHP starts fresh for each request, so it must do all the work again. More items mean more work each time.

Interview Connect

Understanding how PHP handles each request helps you explain how your code scales and why efficient loops matter in real projects.

Self-Check

"What if we added a nested loop inside the foreach to process pairs of items? How would the time complexity change?"