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?"
Practice
Solution
Step 1: Understand what a closure is
A closure is an anonymous function, meaning it has no name and can be created on the fly.Step 2: Recognize closures as callbacks
Closures can be passed as arguments to other functions to customize behavior, making them useful as callbacks.Final Answer:
An anonymous function that can be passed as an argument -> Option CQuick Check:
Closure = anonymous function callback [OK]
- Thinking closures must have names
- Confusing closures with variables
- Believing closures cannot be passed as arguments
Solution
Step 1: Check closure syntax
The correct syntax for an anonymous function uses the keywordfunctionfollowed by parentheses with parameters, then braces with the function body.Step 2: Validate the return statement
The closure must explicitly return the value to be used byarray_map. array_map(function($x) { return $x * 2; }, [1, 2, 3]); correctly returns$x * 2.Final Answer:
array_map(function($x) { return $x * 2; }, [1, 2, 3]); -> Option DQuick Check:
Correct closure syntax = array_map(function($x) { return $x * 2; }, [1, 2, 3]); [OK]
- Omitting parentheses around parameters
- Missing return keyword inside closure
- Using arrow (=>) incorrectly in closure
$numbers = [1, 2, 3];
$result = array_map(function($n) { return $n + 5; }, $numbers);
print_r($result);Solution
Step 1: Understand array_map with closure
The closure adds 5 to each element of the array$numbers.Step 2: Calculate each element
1+5=6, 2+5=7, 3+5=8, so the resulting array is [6, 7, 8].Final Answer:
[6, 7, 8] -> Option BQuick Check:
Each element + 5 = [6,7,8] [OK]
- Confusing original array with result
- Forgetting closure return value
- Misreading array_map behavior
$multiplier = 3;
$numbers = [1, 2, 3];
$result = array_map(function($n) { return $n * $multiplier; }, $numbers);
print_r($result);Solution
Step 1: Check variable scope inside closure
Variables outside a closure are not accessible inside unless passed withuse.Step 2: Identify missing
The closure needsusekeyworduse ($multiplier)to access the external variable.Final Answer:
The variable $multiplier is not accessible inside the closure -> Option AQuick Check:
External vars need use() in closures [OK]
- Assuming closures access all outside variables automatically
- Thinking closures must be named to access variables
- Believing array_map rejects closures
$factor = 4;
$nums = [2, 4, 6];
$results = array_map(function($num) { return $num * $factor; }, $nums);
print_r($results);Solution
Step 1: Understand variable scope in closures
To access an external variable inside a closure, you must explicitly import it usinguse.Step 2: Apply
Modify the closure touse ($factor)syntaxfunction($num) use ($factor) { return $num * $factor; }to access$factor.Final Answer:
Add use ($factor) after the function parentheses -> Option AQuick Check:
use() imports external vars into closures [OK]
- Trying to access external variables without use()
- Using global keyword inside closures incorrectly
- Passing extra arguments to array_map
Ready to prove it?
Pass the test and this pattern moves unknown
