Bird
0
0

Identify the error in this code snippet:

medium📝 Debug Q14 of 15
PHP - Array Functions
Identify the error in this code snippet:
$arr = [1, 2, 3];
array_walk($arr, function($val) {
    $val += 5;
});
print_r($arr);
AThe array must be passed by reference to array_walk.
Barray_walk requires a named function, not an anonymous function.
CCallback function parameter should be passed by reference to modify array.
Dprint_r cannot print arrays modified by array_walk.
Step-by-Step Solution
Solution:
  1. Step 1: Check how callback modifies array

    The callback parameter $val is passed by value, so changes inside do not affect original array.
  2. Step 2: Correct usage for modification

    Passing &$val by reference allows modifying the original array elements.
  3. Final Answer:

    Callback function parameter should be passed by reference to modify array. -> Option C
  4. Quick Check:

    Use & in callback to change array items [OK]
Quick Trick: Use & in callback parameter to modify array elements [OK]
Common Mistakes:
  • Ignoring reference in callback parameter
  • Thinking array_walk needs array by reference
  • Believing anonymous functions are not allowed

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PHP Quizzes