Variable scope in functions in PHP - Time & Space 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.
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 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.
As the array gets bigger, the function does more additions, one for each number.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 additions |
| 100 | 100 additions |
| 1000 | 1000 additions |
Pattern observation: The work grows directly with the number of items in the array.
Time Complexity: O(n)
This means the time to run the function grows in a straight line as the input size grows.
[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.
Understanding how variables inside functions affect performance helps you write clear and efficient code, a skill valued in many coding tasks.
"What if we used a nested loop inside the function to compare each number with every other number? How would the time complexity change?"