← CodeClarityLab Home
Browse by Category
+ added · updated 7d
← Back to glossary

Spaceship Operator <=> (PHP 7.0)

php PHP 7.0+ Beginner

Also Known As

combined comparison operator three-way comparison

TL;DR

The spaceship operator <=> returns -1, 0, or 1 by comparing two values — it replaces verbose if/else comparison callbacks in usort() with a single concise expression.

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

The spaceship operator is only useful for sorting — it is useful anywhere you need a three-way comparison result, including custom ranking and tie-breaking logic.

Why It Matters

usort() callbacks using if/else for comparison are error-prone — spaceship makes the correct implementation obvious and concise.

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

✗ Vulnerable
// PHP 5 comparison in usort:
usort($items, function($a, $b) {
    if ($a->price === $b->price) return 0;
    return $a->price < $b->price ? -1 : 1;
});
✓ Fixed
// 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]
);

Added 22 Mar 2026
Edited 23 Mar 2026
Views 17
Rate this term
No ratings yet
🤖 AI Guestbook educational data only
| |
Last 30 days
0 pings F 2 pings S 0 pings S 0 pings M 0 pings T 0 pings W 0 pings T 0 pings F 0 pings S 1 ping S 0 pings M 1 ping T 1 ping W 0 pings T 0 pings F 1 ping S 0 pings S 0 pings M 0 pings T 0 pings W 1 ping T 0 pings F 1 ping S 0 pings S 0 pings M 0 pings T 0 pings W 0 pings T 0 pings F 1 ping S
No pings yesterday
Amazonbot 6 Google 3 Perplexity 2 Meta AI 1 ChatGPT 1 Ahrefs 1
crawler 11 crawler_json 2 pre-tracking 1
DEV INTEL Tools & Severity
🟢 Low ⚙ Fix effort: Low
⚡ Quick Fix
Replace every usort callback with return $a->field <=> $b->field; — add ?: $a->secondary <=> $b->secondary for multi-key sorts
📦 Applies To
PHP 7.0+ web cli queue-worker
🔗 Prerequisites
🔍 Detection Hints
usort with if($a==$b) return 0 if($a>$b) return 1 pattern; manual ternary comparison in sort callbacks
Auto-detectable: ✓ Yes rector php-cs-fixer
⚠ Related Problems
🤖 AI Agent
Confidence: Medium False Positives: Low ✓ Auto-fixable Fix: Low Context: Line

✓ schema.org compliant