Closures as callbacks in PHP - Time & Space Complexity
We want to understand how the time it takes to run code with closures as callbacks changes when the input grows.
Specifically, how does using a closure inside a function like array_map affect the work done?
Analyze the time complexity of the following code snippet.
$numbers = [1, 2, 3, 4, 5];
$squares = array_map(function($n) {
return $n * $n;
}, $numbers);
print_r($squares);
This code uses a closure as a callback to square each number in an array.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The closure function is called once for each element in the array.
- How many times: Exactly as many times as there are elements in the input array.
As the array gets bigger, the closure runs more times, once per item.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 calls to the closure |
| 100 | 100 calls to the closure |
| 1000 | 1000 calls to the closure |
Pattern observation: The work grows directly in proportion to the number of items.
Time Complexity: O(n)
This means the time to finish grows in a straight line as the input array gets bigger.
[X] Wrong: "Using a closure as a callback makes the code slower in a way that changes the time complexity."
[OK] Correct: The closure itself runs once per item, just like a normal function would, so it does not add extra loops or nested work.
Understanding how closures work as callbacks helps you explain how your code handles repeated tasks clearly and efficiently.
"What if the closure called another function that loops over the entire array inside it? How would the time complexity change?"