Beginner LevelPHP 8+
How does the Combined Comparison Spaceship Operator (<=>) work in PHP 7+ sorting callbacks?
❓ Interview Prompt: Explain the spaceship operator (<=>) return values (-1, 0, 1) and its use in usort() comparison callbacks.
The Spaceship Operator ('<=>') (introduced in PHP 7) performs three-way comparison between two expressions '$a <=> $b':
Return Values:
•
'-1': If '$a' is less than '$b' ('$a < $b').
•
'0': If '$a' is equal to '$b' ('$a == $b').
•
'1': If '$a' is greater than '$b' ('$a > $b').
Best Use Case: 'usort()' Callbacks
Before PHP 7, custom array sorting required verbose 'if/else' blocks returning '-1', '0', or '1'. The spaceship operator condenses comparison callbacks into a single line of code!
Code Implementation Example
php
<?php
// 1. Basic comparison
echo 5 <=> 10; // -1
echo 5 <=> 5; // 0
echo 10 <=> 5; // 1
// 2. Sorting array of users by age using spaceship operator in usort()
$users = [
['name' => 'Alice', 'age' => 30],
['name' => 'Bob', 'age' => 22],
['name' => 'Charlie', 'age' => 25]
];
usort($users, fn($a, $b) => $a['age'] <=> $b['age']);
// $users is now sorted by age ascending: Bob (22), Charlie (25), Alice (30)💡Sorting an array of associative arrays by age using the spaceship operator.
🎯 Interview Key Takeaway
$a <=> $b returns -1, 0, or 1, simplifying custom array sorting in usort() callbacks.
#Spaceship Operator#usort#Sorting#Beginner
Back to all PHP 8+ Questions→