Spaceship Operator <=> (PHP 7.0)
debt(d3/e1/b1/t3)
Closest to 'default linter catches the common case' (d3). The detection_hints list rector and php-cs-fixer, both of which can detect the manual if/else or ternary comparison pattern in usort callbacks automatically — this is a well-known, automatable code pattern replacement.
Closest to 'one-line patch or single-call swap' (e1). The quick_fix is explicit: replace every usort callback with 'return $a->field <=> $b->field;' — a direct single-line substitution per callback, requiring no structural changes.
Closest to 'minimal commitment' (b1). The spaceship operator is a localized syntactic choice inside sort callbacks. It imposes no persistent tax on maintainers outside the immediate comparison expression; the rest of the codebase is unaffected.
Closest to 'minor surprise (one edge case)' (t3). The misconception field notes that developers often think it is only useful for sorting, missing broader three-way comparison use cases. Additionally, common_mistakes flag that PHP type juggling (without strict_types) can produce unexpected ordering. These are minor surprises but not deeply contradictory to intuition.
Also Known As
TL;DR
Explanation
Before PHP 7, writing a comparison callback for usort() required an if/else structure checking equality, greater than, and less than. The spaceship operator <=> compresses this to $a <=> $b. It works on integers, floats, strings, and arrays using PHP's comparison semantics. Multiple sort keys: return $a->priority <=> $b->priority ?: $a->name <=> $b->name. Named for its resemblance to the ASCII art of a spaceship.
Common Misconception
Why It Matters
Common Mistakes
- Forgetting spaceship respects PHP type juggling without strict_types
- Not chaining multiple sort keys with ?: after <=>
- Using manual arithmetic instead of the cleaner <=> operator
Code Examples
// PHP 5 comparison in usort:
usort($items, function($a, $b) {
if ($a->price === $b->price) return 0;
return $a->price < $b->price ? -1 : 1;
});
// PHP 7 spaceship operator:
usort($items, fn($a, $b) => $a->price <=> $b->price);
// Multi-key sort:
usort($items, fn($a, $b) =>
[$a->category, $a->price] <=> [$b->category, $b->price]
);