0
0
PHPprogramming~5 mins

Variable scope in functions in PHP - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Variable scope in functions
O(n)
Understanding Time Complexity

Let's see how the time it takes to run code changes when we use variables inside functions in PHP.

We want to know how variable scope affects the number of steps the program takes.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


function addNumbers($arr) {
    $sum = 0;
    foreach ($arr as $num) {
        $sum += $num;
    }
    return $sum;
}

$numbers = range(1, 100);
echo addNumbers($numbers);
    

This code adds all numbers in an array using a function with a local variable.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Looping through each element of the array inside the function.
  • How many times: Once for each item in the input array.
How Execution Grows With Input

As the array gets bigger, the function does more additions, one for each number.

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

Pattern observation: The work grows directly with the number of items in the array.

Final Time Complexity

Time Complexity: O(n)

This means the time to run the function grows in a straight line as the input size grows.

Common Mistake

[X] Wrong: "Using a variable inside a function makes the code slower in a big way."

[OK] Correct: The variable inside the function just holds values and does not add extra loops or steps beyond the main loop.

Interview Connect

Understanding how variables inside functions affect performance helps you write clear and efficient code, a skill valued in many coding tasks.

Self-Check

"What if we used a nested loop inside the function to compare each number with every other number? How would the time complexity change?"