Challenge - 5 Problems
Closure Callback Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of a closure used as a callback
What is the output of this PHP code using a closure as a callback?
PHP
<?php $numbers = [1, 2, 3, 4]; $result = array_map(function($n) { return $n * 2; }, $numbers); print_r($result); ?>
Attempts:
2 left
💡 Hint
array_map applies the callback to each element and returns a new array.
✗ Incorrect
The closure doubles each number in the array. So 1 becomes 2, 2 becomes 4, and so on.
❓ Predict Output
intermediate2:00remaining
Closure capturing external variable
What will be the output of this PHP code where a closure captures an external variable?
PHP
<?php $factor = 3; $numbers = [1, 2, 3]; $result = array_map(function($n) use ($factor) { return $n * $factor; }, $numbers); print_r($result); ?>
Attempts:
2 left
💡 Hint
The closure uses the 'use' keyword to access $factor inside.
✗ Incorrect
The closure multiplies each number by 3, the value of $factor captured from outside.
❓ Predict Output
advanced2:00remaining
Modifying external variable inside closure
What is the output of this PHP code where a closure modifies an external variable by reference?
PHP
<?php $sum = 0; $numbers = [1, 2, 3]; array_walk($numbers, function($n) use (&$sum) { $sum += $n; }); echo $sum; ?>
Attempts:
2 left
💡 Hint
The closure uses & to modify $sum by reference.
✗ Incorrect
The closure adds each number to $sum, so the total is 1+2+3=6.
❓ Predict Output
advanced2:00remaining
Closure as callback with default argument
What will this PHP code output when using a closure with a default argument as a callback?
PHP
<?php $numbers = [1, 2, 3]; $result = array_map(function($n, $multiplier = 2) { return $n * $multiplier; }, $numbers); print_r($result); ?>
Attempts:
2 left
💡 Hint
array_map passes only one argument to the callback here.
✗ Incorrect
array_map passes only one argument ($n) to the callback, so $multiplier defaults to 2. Each number is doubled: 1→2, 2→4, 3→6.
🧠 Conceptual
expert2:00remaining
Why use closures as callbacks in PHP?
Which is the best explanation for why closures are useful as callbacks in PHP?
Attempts:
2 left
💡 Hint
Think about how closures can access variables outside their own function body.
✗ Incorrect
Closures let you create small functions on the fly that can use variables from where they were created, which is very handy for callbacks.