Bird
0
0

Identify the error in this PHP code using array_map:

medium📝 Debug Q14 of 15
PHP - Array Functions
Identify the error in this PHP code using array_map:
$arr = [1, 2, 3];
$result = array_map('double', $arr);
function double($x) {
  return $x * 2;
}
print_r($result);
Aarray_map requires an anonymous function, not a named function
BNo error, code runs correctly
CFunction double is called before it is defined
DMissing semicolon after array_map call
Step-by-Step Solution
Solution:
  1. Step 1: Check function definition and usage

    The function double is defined after the array_map call, but PHP allows this because functions are hoisted.
  2. Step 2: Verify syntax and function type

    array_map accepts named functions as callbacks, and semicolons are correctly placed.
  3. Final Answer:

    No error, code runs correctly -> Option B
  4. Quick Check:

    Named function callback works fine [OK]
Quick Trick: PHP functions can be used before definition [OK]
Common Mistakes:
  • Assuming function must be defined before use
  • Thinking only anonymous functions work in array_map
  • Missing semicolon errors where none exist

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PHP Quizzes