Bird
0
0

Identify the error in this PHP code using array_filter:

medium📝 Debug Q14 of 15
PHP - Array Functions
Identify the error in this PHP code using array_filter:
$data = [10, 15, 20];
$result = array_filter($data, function($x) {
  if ($x > 15) return true;
});
print_r($result);
AThe callback function does not return false for some values.
Barray_filter requires a third argument for keys.
CThe array must be associative for array_filter to work.
DThe print_r function cannot print arrays.
Step-by-Step Solution
Solution:
  1. Step 1: Check callback return values

    The callback returns true only if $x > 15, but returns nothing (null) otherwise.
  2. Step 2: Understand array_filter behavior

    Callback must return true or false explicitly; null is treated as false but is unclear and risky.
  3. Final Answer:

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

    Callback must return true or false explicitly [OK]
Quick Trick: Always return true or false in callback [OK]
Common Mistakes:
  • Missing explicit false return
  • Thinking array_filter needs 3 arguments
  • Believing print_r can't print arrays

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PHP Quizzes