Assignment and compound assignment in PHP - Time & Space Complexity
Let's see how assignment and compound assignment affect the time it takes for a program to run.
We want to know how the number of steps changes when we assign or update values in variables.
Analyze the time complexity of the following code snippet.
$sum = 0;
for ($i = 0; $i < $n; $i++) {
$sum += $i;
}
echo $sum;
This code adds numbers from 0 up to n-1 using a compound assignment inside a loop.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The addition and compound assignment
$sum += $i;inside the loop. - How many times: This operation runs once for each number from 0 to n-1, so n times.
As n grows, the number of additions grows the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 additions |
| 100 | 100 additions |
| 1000 | 1000 additions |
Pattern observation: The work grows directly with n; doubling n doubles the work.
Time Complexity: O(n)
This means the time to finish grows in a straight line with the size of n.
[X] Wrong: "Compound assignment makes the loop run faster or slower than simple assignment."
[OK] Correct: Compound assignment is just a shorter way to write an operation plus assignment; it does not change how many times the loop runs or how the time grows.
Understanding how simple assignments inside loops affect time helps you explain code efficiency clearly and confidently.
"What if we replaced the loop with a function that adds numbers recursively? How would the time complexity change?"