Bird
0
0

Identify the error in this PHP code snippet:

medium📝 Debug Q6 of 15
PHP - Array Functions
Identify the error in this PHP code snippet:
$arr = [1, 2, 3, 4];
$filtered = array_filter($arr, function($n) {
  if ($n % 2 == 0) {
    return true;
  }
});
AThe callback function does not return false for odd numbers
Barray_filter requires a third parameter
CThe array must be associative
DThe callback function should not use if statements
Step-by-Step Solution
Solution:
  1. Step 1: Analyze callback return values

    The callback returns true for even numbers but returns nothing (null) for odd numbers.
  2. Step 2: Understand array_filter behavior

    Null is treated as false, so odd numbers are filtered out correctly, but explicit false return is better practice.
  3. Final Answer:

    The callback function does not return false for odd numbers -> Option A
  4. Quick Check:

    Callback should return true or false explicitly [OK]
Quick Trick: Always return true or false explicitly in callback [OK]
Common Mistakes:
  • Omitting false return
  • Expecting array_filter needs 3 params
  • Thinking array must be associative

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PHP Quizzes