Bird
0
0

Given an array $numbers = [3, 1, 4, 1, 5], which code snippet correctly sorts it in ascending order using the spaceship operator in a custom comparison function?

hard📝 Application Q15 of 15
PHP - Operators
Given an array $numbers = [3, 1, 4, 1, 5], which code snippet correctly sorts it in ascending order using the spaceship operator in a custom comparison function?
Ausort($numbers, fn($a, $b) => $a == $b);
Busort($numbers, fn($a, $b) => $a <=> $b);
Csort($numbers, fn($a, $b) => $a <=> $b);
Dusort($numbers, fn($a, $b) => $b <=> $a);
Step-by-Step Solution
Solution:
  1. Step 1: Understand sorting with spaceship operator

    To sort ascending, compare $a and $b with $a <=> $b.
  2. Step 2: Check correct function usage

    usort accepts a comparison function; sort does not take a callback.
  3. Final Answer:

    usort($numbers, fn($a, $b) => $a <=> $b); -> Option B
  4. Quick Check:

    Ascending sort uses $a <=> $b with usort [OK]
Quick Trick: Use usort with fn($a,$b) => $a <=> $b for ascending sort [OK]
Common Mistakes:
  • Using sort() with a callback function
  • Reversing $a and $b for ascending order
  • Using equality check instead of comparison

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PHP Quizzes