How PHP executes on the server - Performance & Efficiency
When PHP runs on a server, it processes code step-by-step to create a web page.
We want to see how the time it takes grows as the code or input gets bigger.
Analyze the time complexity of the following code snippet.
<?php
$numbers = [1, 2, 3, 4, 5];
$sum = 0;
foreach ($numbers as $num) {
$sum += $num;
}
echo $sum;
?>
This code adds up all numbers in an array and prints the total.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each number in the array.
- How many times: Once for each number in the array.
As the array gets bigger, the loop runs more times, adding each number.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 additions |
| 100 | 100 additions |
| 1000 | 1000 additions |
Pattern observation: The work grows directly with the number of items.
Time Complexity: O(n)
This means the time to finish grows in a straight line with the input size.
[X] Wrong: "The loop runs a fixed number of times no matter the input size."
[OK] Correct: The loop runs once for each item, so if the array grows, the loop runs more times.
Understanding how PHP runs code step-by-step helps you explain how your programs handle bigger data smoothly.
"What if we replaced the loop with a function that calls itself for each item? How would the time complexity change?"