0
0
PHPprogramming~10 mins

Closures as callbacks 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 define a closure that prints a message.

PHP
<?php
$message = function() { echo [1]; };
$message();
?>
Drag options to blanks, or click blank then click option'
A"Hello, world!"
BHello, world!
Cecho "Hello, world!"
Dprint("Hello, world!")
Attempts:
3 left
💡 Hint
Common Mistakes
Forgetting to put quotes around the string.
Trying to echo inside the closure argument.
2fill in blank
medium

Complete the code to pass a closure as a callback to array_map.

PHP
<?php
$numbers = [1, 2, 3];
$squares = array_map([1], $numbers);
print_r($squares);
?>
Drag options to blanks, or click blank then click option'
Afunction($n) { echo $n; }
Bfunction($n) { return $n * $n; }
Cfn($n) => $n + $n
Dfunction $n { return $n * $n; }
Attempts:
3 left
💡 Hint
Common Mistakes
Missing parentheses around the parameter.
Using echo instead of return.
3fill in blank
hard

Fix the error in the closure that uses a variable from the parent scope.

PHP
<?php
$multiplier = 3;
$multiply = function($n) [1] {
    return $n * $multiplier;
};
echo $multiply(5);
?>
Drag options to blanks, or click blank then click option'
Aimport ($multiplier)
Bwith ($multiplier)
Cuse ($multiplier)
Dcapture ($multiplier)
Attempts:
3 left
💡 Hint
Common Mistakes
Using incorrect keywords like 'with' or 'import'.
Not including the variable in the use clause.
4fill in blank
hard

Fill both blanks to create a closure that modifies a variable by reference.

PHP
<?php
$count = 0;
$increment = [1] use ([2]) {
    $count++;
};
$increment();
echo $count;
?>
Drag options to blanks, or click blank then click option'
Afunction()
B&$count
C$count
Dfunction(&$count)
Attempts:
3 left
💡 Hint
Common Mistakes
Not using the ampersand to pass by reference.
Trying to pass the variable as a parameter instead of use clause.
5fill in blank
hard

Fill all three blanks to create a closure that filters an array using a condition.

PHP
<?php
$words = ['apple', 'bee', 'cat', 'dog'];
$minLength = 3;
$longWords = array_filter($words, function([1]) use ([2]) {
    return strlen([3]) > [2];
});
print_r($longWords);
?>
Drag options to blanks, or click blank then click option'
A$word
B$minLength
D$length
Attempts:
3 left
💡 Hint
Common Mistakes
Using inconsistent variable names.
Not passing the external variable with use.