0
0
PHPprogramming~10 mins

Arrow functions (short closures) in PHP - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to create an arrow function that returns the square of a number.

PHP
$square = fn($x) => [1];
echo $square(4);
Drag options to blanks, or click blank then click option'
A$x + $x
B2 * $x
C$x - 2
D$x * $x
Attempts:
3 left
💡 Hint
Common Mistakes
Using addition instead of multiplication.
Forgetting to use the variable inside the function.
2fill in blank
medium

Complete the code to create an arrow function that adds 10 to a number.

PHP
$addTen = fn($num) => [1];
echo $addTen(5);
Drag options to blanks, or click blank then click option'
A$num + 10
B$num * 10
C10 - $num
D$num - 10
Attempts:
3 left
💡 Hint
Common Mistakes
Subtracting instead of adding.
Multiplying instead of adding.
3fill in blank
hard

Fix the error in the arrow function that should return the length of a string.

PHP
$length = fn($str) => [1];
echo $length('hello');
Drag options to blanks, or click blank then click option'
Acount($str)
Blength($str)
Cstrlen($str)
Dsize($str)
Attempts:
3 left
💡 Hint
Common Mistakes
Using length() which is not a PHP function.
Using count() which is for arrays.
4fill in blank
hard

Fill both blanks to create an arrow function that filters an array to keep only numbers greater than 5.

PHP
$filter = fn($arr) => array_filter($arr, fn($n) => $n [1] [2]);
print_r($filter([3, 7, 2, 9]));
Drag options to blanks, or click blank then click option'
A>
B5
C<
D7
Attempts:
3 left
💡 Hint
Common Mistakes
Using < instead of >.
Using wrong threshold number.
5fill in blank
hard

Fill all three blanks to create an arrow function that maps an array to its elements doubled if they are even.

PHP
$doubleEven = fn($arr) => array_map(fn($x) => [1] ? [2] : [3], $arr);
print_r($doubleEven([1, 2, 3, 4]));
Drag options to blanks, or click blank then click option'
A$x % 2 === 0
B$x * 2
C$x
D$x + 2
Attempts:
3 left
💡 Hint
Common Mistakes
Using addition instead of multiplication for doubling.
Not checking for even numbers correctly.