Challenge - 5 Problems
Closure Mastery in PHP Arrays
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of array_map with closure capturing variable
What is the output of the following PHP code?
PHP
<?php $multiplier = 3; $numbers = [1, 2, 3]; $result = array_map(function($n) use ($multiplier) { return $n * $multiplier; }, $numbers); print_r($result); ?>
Attempts:
2 left
💡 Hint
Closures can capture variables from the surrounding scope using the 'use' keyword.
✗ Incorrect
The closure captures the variable $multiplier by value using 'use ($multiplier)'. Each element in the array is multiplied by 3, producing [3, 6, 9].
❓ Predict Output
intermediate2:00remaining
Effect of modifying captured variable by reference in closure
What will be the output of this PHP code?
PHP
<?php $factor = 2; $numbers = [1, 2, 3]; $result = array_map(function($n) use (&$factor) { return $n * $factor; }, $numbers); $factor = 5; print_r($result); ?>
Attempts:
2 left
💡 Hint
The closure captures the variable by reference, but array_map applies the function immediately.
✗ Incorrect
The closure uses $factor by reference, but array_map calls the closure immediately with $factor = 2. Changing $factor after array_map does not affect the already computed result.
🔧 Debug
advanced2:00remaining
Identify the error in closure used with array_filter
What error does the following PHP code produce?
PHP
<?php $threshold = 10; $values = [5, 15, 20]; $filtered = array_filter($values, function($v) { return $v > $threshold; }); print_r($filtered); ?>
Attempts:
2 left
💡 Hint
Variables outside the closure must be imported with 'use' to be accessible inside.
✗ Incorrect
The closure does not have access to $threshold because it is not imported with 'use'. This causes an undefined variable error.
📝 Syntax
advanced2:00remaining
Syntax error in closure with array_reduce
Which option correctly fixes the syntax error in this PHP code?
PHP
<?php $numbers = [1, 2, 3]; $sum = array_reduce($numbers, function($carry, $item) { $carry += $item return $carry; }); echo $sum; ?>
Attempts:
2 left
💡 Hint
PHP statements must end with semicolons.
✗ Incorrect
The missing semicolon after '$carry += $item' causes a syntax error. Adding it fixes the code.
🚀 Application
expert3:00remaining
Count how many elements satisfy a condition using closure
Given the array $data = [2, 7, 4, 9, 3], which option correctly counts how many numbers are greater than 5 using array_filter and a closure?
PHP
<?php $data = [2, 7, 4, 9, 3]; $count = /* fill in here */; echo $count; ?>
Attempts:
2 left
💡 Hint
array_filter returns filtered elements; count counts them.
✗ Incorrect
Option B filters elements greater than 5 and counts them, producing the correct count 2. Option B returns an array, not a count. Option B counts booleans (all 5). Option B sums booleans but is not asked for.