Closures in array functions in PHP - Time & Space Complexity
When using closures inside array functions, it is important to understand how the time to run the code grows as the array gets bigger.
We want to know how many times the closure runs and how that affects the total work done.
Analyze the time complexity of the following code snippet.
$array = [1, 2, 3, 4, 5];
$result = array_map(function($item) {
return $item * 2;
}, $array);
This code uses a closure inside array_map to double each number in the array.
- Primary operation: The closure function runs once for each element in the array.
- How many times: Exactly as many times as there are elements in the array (n times).
As the array gets bigger, the closure runs more times, directly proportional to the number of elements.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 closure calls |
| 100 | 100 closure calls |
| 1000 | 1000 closure calls |
Pattern observation: The work grows in a straight line with the input size; doubling the array size doubles the work.
Time Complexity: O(n)
This means the time to finish grows directly with the number of items in the array.
[X] Wrong: "The closure runs only once, so the time is constant no matter the array size."
[OK] Correct: The closure is called for every element, so more elements mean more calls and more time.
Understanding how closures work inside array functions helps you explain how your code scales and shows you can reason about performance clearly.
"What if the closure inside array_map called another function that itself loops over the array? How would the time complexity change?"