Bird
0
0

What is the output of the following PHP code?

medium📝 Predict Output Q13 of 15
PHP - Array Functions
What is the output of the following PHP code?
$arr = [1, 2, 3, 4, 5];
$result = array_filter($arr, fn($n) => $n % 2 === 0);
print_r($result);
AArray ( [0] => 2 [1] => 4 )
BArray ( [0] => 1 [2] => 3 [4] => 5 )
CArray ( [1] => 2 [3] => 4 )
DArray ( [0] => 2 [2] => 4 )
Step-by-Step Solution
Solution:
  1. Step 1: Understand the callback function

    The callback keeps numbers where $n % 2 === 0, meaning even numbers.
  2. Step 2: Identify even numbers and keys

    Even numbers in the array are 2 and 4 at keys 1 and 3 respectively.
  3. Final Answer:

    Array ( [1] => 2 [3] => 4 ) -> Option C
  4. Quick Check:

    Only even numbers kept with original keys [OK]
Quick Trick: Check which elements return true, keys stay same [OK]
Common Mistakes:
  • Assuming keys are reindexed
  • Keeping odd numbers by mistake
  • Confusing array keys with values

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PHP Quizzes