Return values in PHP - Time & Space Complexity
Let's see how the time it takes to run code changes when we use return values in PHP functions.
We want to know how the number of steps grows as the input changes.
Analyze the time complexity of the following code snippet.
<?php
function sumArray(array $numbers) {
$total = 0;
foreach ($numbers as $num) {
$total += $num;
}
return $total;
}
$values = [1, 2, 3, 4, 5];
echo sumArray($values);
?>
This code adds all numbers in an array and returns the total sum.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each number in the array.
- How many times: Once for every 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.
Time Complexity: O(n)
This means the time to finish grows in a straight line with the input size.
[X] Wrong: "Return statements make the function run faster or slower depending on the value returned."
[OK] Correct: The return just sends back the result; it does not add extra loops or steps that change how long the function takes overall.
Understanding how return values fit into time complexity helps you explain your code clearly and shows you know what parts affect speed.
"What if the function returned the sum of only the first half of the array? How would the time complexity change?"