0
0
PHPprogramming~10 mins

Closures in array functions 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 filter numbers greater than 5 using array_filter and a closure.

PHP
<?php
$numbers = [2, 5, 8, 1, 10];
$filtered = array_filter($numbers, function($num) {
    return $num [1] 5;
});
print_r($filtered);
?>
Drag options to blanks, or click blank then click option'
A!=
B<
C==
D>
Attempts:
3 left
💡 Hint
Common Mistakes
Using '<' instead of '>' will filter numbers less than 5.
Using '==' will only keep numbers equal to 5.
2fill in blank
medium

Complete the code to double each number in the array using array_map and a closure.

PHP
<?php
$numbers = [1, 2, 3, 4];
$doubled = array_map(function($num) {
    return $num [1] 2;
}, $numbers);
print_r($doubled);
?>
Drag options to blanks, or click blank then click option'
A+
B/
C*
D-
Attempts:
3 left
💡 Hint
Common Mistakes
Using '+' will add 2 instead of doubling.
Using '-' or '/' will not double the number.
3fill in blank
hard

Fix the error in the closure to correctly filter even numbers using array_filter.

PHP
<?php
$numbers = [1, 2, 3, 4, 5];
$evens = array_filter($numbers, function($num) {
    return $num [1] 2 == 0;
});
print_r($evens);
?>
Drag options to blanks, or click blank then click option'
A%
B/
C*
D+
Attempts:
3 left
💡 Hint
Common Mistakes
Using '/' will perform division, not remainder.
Using '*' or '+' will not check for even numbers.
4fill in blank
hard

Fill both blanks to create an array of squares for numbers greater than 3 using array_map and array_filter with closures.

PHP
<?php
$numbers = [1, 2, 3, 4, 5];
$filtered = array_filter($numbers, function($num) {
    return $num [1] 3;
});
$squares = array_map(function($num) {
    return $num [2] $num;
}, $filtered);
print_r($squares);
?>
Drag options to blanks, or click blank then click option'
A>
B*
C+
D<
Attempts:
3 left
💡 Hint
Common Mistakes
Using '<' will filter numbers less than 3.
Using '+' instead of '*' will add numbers instead of squaring.
5fill in blank
hard

Fill all three blanks to create an associative array with uppercase keys and values filtered by length greater than 4 using closures.

PHP
<?php
$words = ['apple', 'bat', 'carrot', 'dog'];
$result = array_filter(array_combine(array_map(function($word) {
    return [1];
}, $words), $words), function($word) {
    return strlen($word) [2] 4;
});
$result = array_map(function($word) {
    return [3];
}, $result);
print_r($result);
?>
Drag options to blanks, or click blank then click option'
Astrtoupper($word)
B>
D<
Attempts:
3 left
💡 Hint
Common Mistakes
Using '<' will filter words with length less than or equal to 4.
Not converting keys or values to uppercase will not meet the requirement.