Anonymous function syntax in PHP - Time & Space Complexity
Let's see how the time needed to run an anonymous function changes as we use it in different ways.
We want to know how the number of steps grows when the function is called multiple times.
Analyze the time complexity of the following code snippet.
$numbers = [1, 2, 3, 4, 5];
$sum = 0;
$add = function($n) use (&$sum) {
$sum += $n;
};
foreach ($numbers as $num) {
$add($num);
}
This code defines an anonymous function to add numbers to a sum, then calls it for each number in the list.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Calling the anonymous function inside a loop.
- How many times: Once for each item in the array.
Each time we add one more number, the function runs one more time.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 calls to the function |
| 100 | 100 calls to the function |
| 1000 | 1000 calls to the function |
Pattern observation: The work grows evenly as the list gets bigger.
Time Complexity: O(n)
This means the time to finish grows directly with the number of items we process.
[X] Wrong: "Anonymous functions run slower and add extra hidden loops."
[OK] Correct: The anonymous function itself runs once per call, just like a normal function, so it doesn't add extra repeated work beyond how many times you call it.
Understanding how anonymous functions behave helps you explain your code clearly and shows you know how function calls affect performance.
"What if the anonymous function contained a loop inside it? How would the time complexity change?"