Bird
0
0

What is wrong with this code?

medium📝 Debug Q7 of 15
PHP - Array Functions
What is wrong with this code?
$arr = [1, 2, 3, 4];
$filtered = array_filter($arr, fn($n) => $n > 2);
print_r($filtered);

Output is empty array.
Aarray_filter does not work with arrow functions
BThe callback should return false for numbers > 2
CThe array must be passed by reference
DThe arrow function syntax requires PHP 7.4+, older versions fail
Step-by-Step Solution
Solution:
  1. Step 1: Check PHP version compatibility

    Arrow functions (fn) are supported from PHP 7.4 onwards.
  2. Step 2: Understand why output is empty

    If run on older PHP versions, arrow function syntax causes failure, resulting in empty output.
  3. Final Answer:

    The arrow function syntax requires PHP 7.4+, older versions fail -> Option D
  4. Quick Check:

    Arrow functions need PHP 7.4+ [OK]
Quick Trick: Use arrow functions only in PHP 7.4+ [OK]
Common Mistakes:
  • Assuming callback logic is wrong
  • Thinking array_filter rejects arrow functions
  • Passing array by reference unnecessarily

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PHP Quizzes