Operator precedence and evaluation in PHP - Time & Space Complexity
When we use operators in PHP, the order they run in can affect how many steps the program takes.
We want to see how the order of operations changes the work done as input grows.
Analyze the time complexity of the following code snippet.
$sum = 0;
for ($i = 0; $i < $n; $i++) {
$sum += $i * 2 + 1;
}
echo $sum;
This code adds up a series of numbers calculated with operators inside a loop.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The loop runs and does addition and multiplication each time.
- How many times: The loop runs once for each number from 0 up to n-1.
Each time n gets bigger, the loop runs more times, doing the same steps each time.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 times the addition and multiplication |
| 100 | About 100 times the addition and multiplication |
| 1000 | About 1000 times the addition and multiplication |
Pattern observation: The work grows directly with n; if n doubles, work doubles.
Time Complexity: O(n)
This means the time to finish grows in a straight line as the input size grows.
[X] Wrong: "Because there are multiple operators inside the loop, the time grows faster than n."
[OK] Correct: The operators run a fixed number of times per loop, so they only add a small constant amount of work each time, not extra loops.
Understanding how operator order affects repeated work helps you explain code efficiency clearly and confidently.
"What if we added another loop inside the current loop? How would the time complexity change?"