0
0
PHPprogramming~20 mins

Array filter function in PHP - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Array Filter Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2: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);
?>
AArray ( [1] => 2 [3] => 4 )
BArray ( [0] => 2 [1] => 4 )
CArray ( [0] => 1 [2] => 3 [4] => 5 )
DArray ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 )
Attempts:
2 left
💡 Hint
Remember that array_filter preserves keys by default.
Predict Output
intermediate
2: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);
?>
AArray ( [0] => 1 [2] => 2 [4] => 3 )
BArray ( [0] => 0 [1] => 1 [2] => false [3] => 2 [4] => '' [5] => 3 )
CArray ( [0] => 1 [1] => 2 [2] => 3 )
DArray ( [1] => 1 [3] => 2 [5] => 3 )
Attempts:
2 left
💡 Hint
Without a callback, array_filter removes values that are falsey.
🔧 Debug
advanced
2: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;
}
?>
AIt runs correctly and outputs even numbers with keys preserved.
BIt causes a syntax error because function names cannot be passed as strings.
CIt causes a fatal error because the function is_even is called before it is defined.
DIt causes a runtime error because array_filter expects an anonymous function.
Attempts:
2 left
💡 Hint
In PHP, functions must be defined before they are used if called by name as a string.
📝 Syntax
advanced
2: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?
A$result = array_filter($array, fn($x) => $x % 2 == 1);
B$result = array_filter($array, function($x) { return $x % 2 == 1; });
C$result = array_filter($array, function($x) { $x % 2 == 1 });
D$result = array_filter($array, fn $x => $x % 2 == 1);
Attempts:
2 left
💡 Hint
Anonymous functions need a return statement unless using arrow functions.
🚀 Application
expert
2: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;
?>
A3
B5
C4
D2
Attempts:
2 left
💡 Hint
Check the length of each fruit name carefully.