Why loops are needed in PHP - Performance Analysis
Loops help us repeat actions many times without writing the same code again and again.
We want to see how the time to run code changes when we use loops with bigger inputs.
Analyze the time complexity of the following code snippet.
$numbers = [1, 2, 3, 4, 5];
$sum = 0;
foreach ($numbers as $num) {
$sum += $num;
}
echo $sum;
This code adds up all numbers in a list using a loop.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Adding each number to the sum inside the loop.
- How many times: Once for each number in the list.
Explain the growth pattern intuitively.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 additions |
| 100 | 100 additions |
| 1000 | 1000 additions |
Pattern observation: The number of steps grows directly with the number of items.
Time Complexity: O(n)
This means the time to finish grows in a straight line as the list gets bigger.
[X] Wrong: "The loop runs a fixed number of times no matter the list size."
[OK] Correct: The loop runs once for each item, so if the list grows, the loop runs more times.
Understanding how loops affect time helps you explain your code clearly and shows you know how programs handle bigger data.
"What if we used two loops one inside the other to add numbers? How would the time complexity change?"