0
0
PHPprogramming~20 mins

Arrow functions (short closures) in PHP - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Arrow Function Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of a simple arrow function
What is the output of the following PHP code using an arrow function?
PHP
<?php
$multiplier = 3;
$numbers = [1, 2, 3];
$results = array_map(fn($n) => $n * $multiplier, $numbers);
print_r($results);
?>
AArray ( [0] => 3 [1] => 6 [2] => 9 )
BArray ( [0] => 1 [1] => 2 [2] => 3 )
CArray ( [0] => 0 [1] => 0 [2] => 0 )
DFatal error: Uncaught Error: Undefined variable: multiplier
Attempts:
2 left
💡 Hint
Remember that arrow functions automatically capture variables from the parent scope.
Predict Output
intermediate
1:30remaining
Arrow function with multiple parameters
What will this PHP code output?
PHP
<?php
$adder = fn($a, $b) => $a + $b;
echo $adder(5, 7);
?>
AError: Too few arguments
B57
C12
DError: Syntax error
Attempts:
2 left
💡 Hint
Arrow functions can take multiple parameters just like normal functions.
🔧 Debug
advanced
2:30remaining
Why does this arrow function cause an error?
Consider this PHP code snippet. What error will it produce and why?
PHP
<?php
$factor = 2;
$func = fn($x) => $x * $factor;
$factor = 'three';
echo $func(4);
?>
AOutputs 12 because arrow functions use the variable's value at call time
BOutputs 8 because arrow functions capture variables by value at definition time
CFatal error: Cannot use string 'three' as a number
DParse error: syntax error
Attempts:
2 left
💡 Hint
Arrow functions capture variables from the parent scope by value, not by reference.
📝 Syntax
advanced
2:00remaining
Identify the syntax error in arrow function usage
Which option contains a syntax error in the arrow function?
A$f = fn($x) => $x + 1;
B$f = fn($x) => $x * 2;
C$f = fn($x) { return $x * 2; };
D$f = fn($x) => { $x * 2; };
Attempts:
2 left
💡 Hint
Arrow functions must have a single expression without braces or use return inside braces in normal closures.
🚀 Application
expert
3:00remaining
Using arrow functions to filter and transform arrays
Given the array $nums = [1, 2, 3, 4, 5, 6], which option produces an array of squares of even numbers only?
PHP
<?php
$nums = [1, 2, 3, 4, 5, 6];
// Your code here
?>
Aarray_map(fn($n) => $n * $n, array_filter($nums, fn($n) => $n % 2 === 0));
B;)0 ==! 2 % n$ >= )n$(nf ,)smun$ ,n$ * n$ >= )n$(nf(pam_yarra(retlif_yarra
Carray_map(fn($n) => $n * $n, array_filter($nums, fn($n) => $n % 2));
Darray_filter(array_map(fn($n) => $n * $n, $nums), fn($n) => $n % 2 !== 0);
Attempts:
2 left
💡 Hint
Filter first to keep even numbers, then map to square them.