0
0
PHPprogramming~10 mins

Array filter function 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 the array and keep only even numbers.

PHP
<?php
$numbers = [1, 2, 3, 4, 5];
$evens = array_filter($numbers, function($n) {
    return $n [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 '==' instead of '%' causes wrong filtering.
Using '+' instead of '%' causes syntax errors.
2fill in blank
medium

Complete the code to filter the array and keep only strings with length greater than 3.

PHP
<?php
$words = ['cat', 'lion', 'dog', 'elephant'];
$longWords = array_filter($words, function($word) {
    return strlen($word) [1] 3;
});
print_r($longWords);
?>
Drag options to blanks, or click blank then click option'
A==
B>
C===
D<
Attempts:
3 left
💡 Hint
Common Mistakes
Using '<' filters shorter words instead.
Using '===' compares type and value, not suitable here.
3fill in blank
hard

Fix the error in the code to filter numbers greater than 10.

PHP
<?php
$nums = [5, 12, 8, 20];
$filtered = array_filter($nums, function($num) {
    return $num [1] 10;
});
print_r($filtered);
?>
Drag options to blanks, or click blank then click option'
A<
B=
C==
D>
Attempts:
3 left
💡 Hint
Common Mistakes
Using '=' causes assignment, not comparison.
Using '<' filters smaller numbers.
4fill in blank
hard

Complete the code to filter words starting with letter 'a'.

PHP
<?php
$words = 'apple', 'banana', 'avocado', 'cherry'];
$filtered = array_filter($words, function($word) {
    return $word[0 [1] 'a';
});
print_r($filtered);
?>
Drag options to blanks, or click blank then click option'
A[
B==
C===
D(
Attempts:
3 left
💡 Hint
Common Mistakes
Using parentheses instead of brackets to access characters.
Using '===' might cause issues if types differ.
5fill in blank
hard

Fill all three blanks to filter an associative array for values greater than 50.

PHP
<?php
$scores = ['Alice' => 45, 'Bob' => 75, 'Carol' => 60];
$highScores = array_filter($scores, function([1]) {
    return [2] [3] 50;
});
print_r($highScores);
?>
Drag options to blanks, or click blank then click option'
Ascore
B$score
C>
D$value
Attempts:
3 left
💡 Hint
Common Mistakes
Using variable names without $ sign.
Using '<' instead of '>' causes wrong filtering.