PHP process model per request - Time & Space 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.
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.
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.
As the number of items grows, the work grows too.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 loops, 10 prints |
| 100 | 100 loops, 100 prints |
| 1000 | 1000 loops, 1000 prints |
Pattern observation: The work grows directly with the number of items. Double the items, double the work.
Time Complexity: O(n)
This means the time PHP takes grows in a straight line with the number of items it processes.
[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.
Understanding how PHP handles each request helps you explain how your code scales and why efficient loops matter in real projects.
"What if we added a nested loop inside the foreach to process pairs of items? How would the time complexity change?"