Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Using '==' instead of '%' causes wrong filtering.
Using '+' instead of '%' causes syntax errors.
✗ Incorrect
The modulo operator (%) returns the remainder. Using $n % 2 === 0 checks if a number is even.
2fill in blank
mediumComplete 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Using '<' filters shorter words instead.
Using '===' compares type and value, not suitable here.
✗ Incorrect
We want words longer than 3 characters, so use '>' to compare length.
3fill in blank
hardFix 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Using '=' causes assignment, not comparison.
Using '<' filters smaller numbers.
✗ Incorrect
To filter numbers greater than 10, use the '>' operator.
4fill in blank
hardComplete 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Using parentheses instead of brackets to access characters.
Using '===' might cause issues if types differ.
✗ Incorrect
Use square brackets to get the first character and '==' to compare it to 'a'.
5fill in blank
hardFill 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Using variable names without $ sign.
Using '<' instead of '>' causes wrong filtering.
✗ Incorrect
The function parameter is '$score', and we compare '$score > 50' to filter values greater than 50.