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?"
Practice
closure inside PHP array functions like array_map or array_filter?Solution
Step 1: Understand what a closure is
A closure is a small, unnamed function that can be used directly where needed.Step 2: Role in array functions
Closures let you write the logic for processing each array element inline, making code concise and clear.Final Answer:
To define a small, unnamed function that processes array elements inline -> Option AQuick Check:
Closure = small inline function [OK]
- Thinking closures declare global variables
- Confusing closures with array conversion functions
- Assuming closures create arrays without functions
array_filter to keep only even numbers from an array $numbers?Solution
Step 1: Check closure syntax
Correct closure syntax usesfunction($param) { return expression; }.Step 2: Validate each option
array_filter($numbers, function($n) { return $n % 2 == 0; }); uses correct syntax with return statement. array_filter($numbers, function $n { return $n % 2 == 0; }); misses parentheses. array_filter($numbers, function($n) => $n % 2 == 0;); uses arrow syntax incorrectly. array_filter($numbers, function($n) { $n % 2 == 0; }); lacks return keyword.Final Answer:
array_filter($numbers, function($n) { return $n % 2 == 0; }); -> Option BQuick Check:
Closure syntax needs parentheses and return [OK]
- Omitting parentheses around parameters
- Using arrow syntax incorrectly in PHP 7+
- Forgetting to return a value inside closure
$nums = [1, 2, 3, 4];
$result = array_map(function($x) { return $x * 3; }, $nums);
print_r($result);Solution
Step 1: Understand array_map with closure
array_map applies the closure to each element, multiplying by 3.Step 2: Calculate each element
1*3=3, 2*3=6, 3*3=9, 4*3=12, so result is [3, 6, 9, 12].Final Answer:
[3, 6, 9, 12] -> Option CQuick Check:
Multiply each by 3 = [3,6,9,12] [OK]
- Expecting original array unchanged
- Confusing array_map with array_filter
- Thinking output is a string, not array
array_filter:
$values = [10, 15, 20];
$filtered = array_filter($values, function($v) {
if ($v > 10) {
return true;
}
});
print_r($filtered);Solution
Step 1: Analyze closure return behavior
The closure returns true only if value > 10, but returns nothing (null) otherwise.Step 2: Understand array_filter behavior
array_filter expects explicit boolean returns. Returning implicit null (falsy) for values <=10 removes them but can cause unexpected filtering behavior.Final Answer:
The closure does not return false for values <= 10, causing unexpected filtering -> Option AQuick Check:
Closure must return true or false explicitly [OK]
- Not returning false explicitly in closure
- Thinking closures must be named functions
- Missing array parameter in array_filter
$data = [1, 2, 3, 4, 5, 6], how can you use a closure with array_filter and array_map together to get an array of squares of only the odd numbers?Solution
Step 1: Filter odd numbers first
Use array_filter with closure to keep only odd numbers:fn($x) => $x % 2 !== 0.Step 2: Map squares of filtered numbers
Apply array_map with closure to square each filtered number:fn($x) => $x * $x.Step 3: Combine calls correctly
Pass filtered array as second argument to array_map, so filtering happens before mapping.Final Answer:
array_map(fn($x) => $x * $x, array_filter($data, fn($x) => $x % 2 !== 0)); -> Option DQuick Check:
Filter odds then map squares [OK]
- Reversing order of array_map and array_filter
- Passing arguments in wrong order
- Using array_map or array_filter with wrong parameter order
Ready to prove it?
Pass the test and this pattern moves unknown
