0
0
PHPprogramming~5 mins

Assignment and compound assignment in PHP - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Assignment and compound assignment
O(n)
Understanding Time 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.

Scenario Under Consideration

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 Repeating Operations

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.
How Execution Grows With Input

As n grows, the number of additions grows the same way.

Input Size (n)Approx. Operations
1010 additions
100100 additions
10001000 additions

Pattern observation: The work grows directly with n; doubling n doubles the work.

Final Time Complexity

Time Complexity: O(n)

This means the time to finish grows in a straight line with the size of n.

Common Mistake

[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.

Interview Connect

Understanding how simple assignments inside loops affect time helps you explain code efficiency clearly and confidently.

Self-Check

"What if we replaced the loop with a function that adds numbers recursively? How would the time complexity change?"