Challenge - 5 Problems
Array Filter Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of array_filter with callback
What is the output of the following PHP code?
PHP
<?php $array = [1, 2, 3, 4, 5]; $result = array_filter($array, fn($x) => $x % 2 === 0); print_r($result); ?>
Attempts:
2 left
💡 Hint
Remember that array_filter preserves keys by default.
✗ Incorrect
array_filter keeps elements where the callback returns true. Here, it keeps even numbers 2 and 4, preserving their original keys 1 and 3.
❓ Predict Output
intermediate2:00remaining
Effect of array_filter without callback
What will be the output of this PHP code?
PHP
<?php $array = [0, 1, false, 2, '', 3]; $result = array_filter($array); print_r($result); ?>
Attempts:
2 left
💡 Hint
Without a callback, array_filter removes values that are falsey.
✗ Incorrect
array_filter without a callback removes falsey values like 0, false, and empty string, keeping only 1, 2, and 3 with their original keys.
🔧 Debug
advanced2:00remaining
Why does this array_filter code cause an error?
Consider this PHP code snippet. Why does it cause an error?
PHP
<?php $array = [1, 2, 3, 4]; $result = array_filter($array, 'is_even'); print_r($result); function is_even($n) { return $n % 2 == 0; } ?>
Attempts:
2 left
💡 Hint
In PHP, functions must be defined before they are used if called by name as a string.
✗ Incorrect
The function is_even is defined after it is used in array_filter, causing a fatal error because PHP does not find the function at the time of call.
📝 Syntax
advanced2:00remaining
Identify the syntax error in this array_filter usage
Which option shows the correct way to use array_filter with a callback that filters odd numbers?
Attempts:
2 left
💡 Hint
Anonymous functions need a return statement unless using arrow functions.
✗ Incorrect
Option B correctly uses a function with a return statement. Option B is valid PHP 7.4+ arrow function syntax but uses == instead of === (still valid but less strict). Option B is invalid syntax. Option B misses return statement causing no filtering.
🚀 Application
expert2:00remaining
Count how many elements remain after filtering
Given the array and filter below, how many elements will remain in the result?
PHP
<?php $array = ['apple', 'banana', 'cherry', 'date', 'fig']; $result = array_filter($array, fn($fruit) => strlen($fruit) > 4); $count = count($result); echo $count; ?>
Attempts:
2 left
💡 Hint
Check the length of each fruit name carefully.
✗ Incorrect
The fruits with length greater than 4 are 'apple' (5), 'banana' (6), and 'cherry' (6). 'date' (4) and 'fig' (3) are excluded. So 3 elements remain.