Spaceship Operator

Ma Mahalakshmi V Updated 14 Nov 2026
6 min read ·Lesson 44 of 256

What Is the Spaceship Operator?

In simple terms: The spaceship operator <=> compares two values and tells you which one is smaller, or whether they are equal — all in one result.

Technically: <=> is the three-way comparison operator, introduced in PHP 7.0. It returns an integer:

ExpressionResult
$a <=> $b when $a < $b-1
$a <=> $b when $a == $b0
$a <=> $b when $a > $b1

The name comes from its shape, which resembles a small spaceship.

Why It Exists

Sorting functions such as usort() need a comparison function that answers "should $a come before, after, or at the same position as $b?" by returning a negative number, zero, or a positive number. Before PHP 7, this required a nested ternary or several if statements. <=> produces exactly that answer in one expression.


Basic Usage

Example

<?php
var_dump(1 <=> 2);
var_dump(2 <=> 2);
var_dump(3 <=> 2);

var_dump(1.5 <=> 1.5);
var_dump("apple" <=> "banana");
var_dump("a" <=> "B");
var_dump("10" <=> "9");
var_dump([1, 2, 3] <=> [1, 2, 4]);

Output

int(-1)
int(0)
int(1)
int(0)
int(-1)
int(1)
int(1)
int(-1)

How It Works

<=> follows the same rules as the <, ==, and > operators:

  • Numbers are compared numerically.
  • Non-numeric strings are compared byte by byte, so "a" (97) is greater than "B" (66) — uppercase letters sort before lowercase ones.
  • Numeric strings ("10", "9") are compared as numbers, so "10" <=> "9" is 1.
  • Arrays are compared element by element (an array with fewer elements is smaller).

Since all type-juggling rules of loose comparison apply, compare values of the same type for predictable results.


Equivalent Without the Spaceship

The spaceship operator replaces this pattern:

<?php
function compareOld(int $a, int $b): int
{
    if ($a < $b) {
        return -1;
    }

    if ($a > $b) {
        return 1;
    }

    return 0;
}

function compareNew(int $a, int $b): int
{
    return $a <=> $b;
}

var_dump(compareOld(4, 9) === compareNew(4, 9));

Output

bool(true)

Sorting With usort()

How usort() Uses the Result

usort($array, $callback) sorts an array using your comparison function. For each pair of elements, the callback must return:

  • a negative number if $a should come before $b,
  • zero if they are equal for sorting purposes,
  • a positive number if $a should come after $b.

$a <=> $b gives ascending order. Swapping the operands, $b <=> $a, gives descending order.

Example: Sorting Products by Price

<?php
$products = [
    ['name' => 'Mouse', 'price' => 799],
    ['name' => 'Keyboard', 'price' => 1499],
    ['name' => 'USB Cable', 'price' => 199],
    ['name' => 'Webcam', 'price' => 1499],
];

usort($products, fn(array $a, array $b): int => $a['price'] <=> $b['price']);

foreach ($products as $product) {
    echo "{$product['name']}: ₹{$product['price']}\n";
}

Output

USB Cable: ₹199
Mouse: ₹799
Keyboard: ₹1499
Webcam: ₹1499

How It Works

  • The arrow function receives two products and compares their prices.
  • Keyboard and Webcam have the same price, so the comparison returns 0. Since PHP 8.0, sorting is stable: elements that compare as equal keep their original order, so Keyboard stays before Webcam.
  • usort() sorts the array in place and re-indexes it from 0.

Descending Order

<?php
usort($products, fn(array $a, array $b): int => $b['price'] <=> $a['price']);

Placing $b on the left reverses the order: the most expensive products come first.


Sorting by Multiple Fields

Arrays are compared element by element, from the first element to the last. This makes multi-level sorting very concise: build an array of sort keys for each item.

Example: Price Descending, Then Name Ascending

<?php
$products = [
    ['name' => 'Webcam', 'price' => 1499],
    ['name' => 'Mouse', 'price' => 799],
    ['name' => 'Keyboard', 'price' => 1499],
    ['name' => 'USB Cable', 'price' => 199],
];

usort($products, fn(array $a, array $b): int =>
    [$b['price'], $a['name']] <=> [$a['price'], $b['name']]
);

foreach ($products as $product) {
    echo "{$product['name']}: ₹{$product['price']}\n";
}

Output

Keyboard: ₹1499
Webcam: ₹1499
Mouse: ₹799
USB Cable: ₹199

How It Works

  1. The left array is [$b['price'], $a['name']] and the right array is [$a['price'], $b['name']].
  2. PHP first compares the first elements: $b['price'] <=> $a['price']. Because $b is on the left, higher prices come first (descending).
  3. Only when prices are equal does PHP compare the second elements: $a['name'] <=> $b['name'], which sorts names ascending.
  4. Keyboard and Webcam share a price, so they are ordered by name.

To change the direction of any key, swap $a and $b for that position only.


Sorting Other Kinds of Data

Dates

DateTime and DateTimeImmutable objects can be compared directly:

<?php
$events = [
    ['title' => 'Workshop', 'date' => new DateTimeImmutable('2026-11-20')],
    ['title' => 'Webinar', 'date' => new DateTimeImmutable('2026-10-15')],
    ['title' => 'Meetup', 'date' => new DateTimeImmutable('2026-12-02')],
];

usort($events, fn($a, $b) => $a['date'] <=> $b['date']);

foreach ($events as $event) {
    echo $event['date']->format('d M') . " - {$event['title']}\n";
}

Output

15 Oct - Webinar
20 Nov - Workshop
02 Dec - Meetup

Case-Insensitive and Natural String Order

<=> compares strings byte by byte. That order is not what people expect when text mixes uppercase and lowercase letters or contains numbers:

<?php
$files = ['img12.png', 'IMG2.png', 'img10.png', 'img1.png'];

usort($files, fn($a, $b) => $a <=> $b);
echo implode(', ', $files) . "\n";

usort($files, 'strnatcasecmp');
echo implode(', ', $files) . "\n";

Output

IMG2.png, img1.png, img10.png, img12.png
img1.png, IMG2.png, img10.png, img12.png
  • With <=>, IMG2.png comes first only because uppercase letters have lower byte values than lowercase ones. The digits are compared one character at a time, so img10 would also come before a lowercase img2.
  • strnatcasecmp() ignores case and treats embedded numbers as numbers, giving the order a person expects: 1, 2, 10, 12. It can be passed directly as the callback by name.

For names in specific languages, use Collator::compare() from the intl extension, which follows the sorting rules of a locale.


Common Mistakes

Returning a Boolean From a Comparison Callback

<?php
$numbers = [3, 1, 2];
usort($numbers, fn($a, $b) => $a > $b);

Output

PHP Deprecated:  usort(): Returning bool from comparison function is deprecated, return an integer less than, equal to, or greater than zero in /path/script.php on line 3

A boolean only says "greater or not" — it cannot express "less than" and "equal" separately. PHP 8 still sorts the array by working around it, but warns that this is deprecated. Return $a <=> $b.

Subtracting Values Instead of Comparing

usort($items, fn($a, $b) => $a['rating'] - $b['rating']);

Subtraction seems to work for integers, but with floats it fails: a difference such as 0.4 is converted to the integer 0, so the two items are treated as equal and may end up in the wrong order. With very large integers, subtraction can also overflow. <=> has neither problem.

Comparing Mixed Types

Effect: Loose comparison rules (for example, numeric strings compared as numbers) produce surprising orders.

Fix: Normalize values to one type before sorting.

Expecting <=> to Sort Strings Naturally or Case-Insensitively

Effect: Uppercase words come first; "img10" sorts before "img2".

Fix: Use strcasecmp(), strnatcasecmp(), or Collator.

Reversing Direction for All Keys by Accident

Effect: In multi-key sorts, swapping the entire arrays reverses every key.

Fix: Swap $a and $b only for the keys that should be descending.


Best Practices

  • Use $a <=> $b for ascending and $b <=> $a for descending comparisons.
  • Sort by several fields by comparing arrays of keys.
  • Return integers from comparison callbacks — never booleans, and avoid subtraction.
  • Compare values of a consistent type; compare dates as date objects.
  • Use dedicated functions (strnatcasecmp(), Collator) for human-friendly string ordering.

Official reference: https://www.php.net/manual/en/language.operators.comparison.php

0 Comments

Reviewed before they appear

No comments yet.

PHP
PHP Tutorial Index PHP Home PHP Intro PHP Install PHP Built-in Web Server PHP Syntax PHP Tags PHP and HTML PHP Comments PHP Multiline Comments PHP Variables Variables Scope Static Variables Variable Variables PHP Echo / Print PHP printf / sprintf PHP Data Types PHP Booleans PHP NULL PHP Strings String Functions Modify Strings Concatenate Strings Slicing Strings Escape Characters String Interpolation Heredoc and Nowdoc Search in Strings Multibyte Strings PHP Floats PHP Casting PHP Type Juggling PHP Math PHP Random Numbers PHP Constants PHP Magic Constants PHP Operators Arithmetic Operators Assignment Operators Comparison Operators Increment / Decrement Operators Logical Operators Null Coalescing Operator Spaceship Operator Operator Precedence PHP If...Else...Elseif PHP If PHP If Operators PHP If...Else PHP Shorthand if PHP Nested if PHP Switch PHP Match Alternative Syntax PHP Loops While Loop Do While Loop For Loop Foreach Loop Nested Loops Break Statement Continue Statement PHP Functions User-defined Functions Function Arguments Default Argument Values Pass by Reference Named Arguments Variadic Functions Return Values Type Declarations in Functions Recursive Functions Variable Functions Anonymous Functions Closures Arrow Functions First-class Callable Syntax PHP Arrays Indexed Arrays Associative Arrays Create Arrays Access Array Items Update Array Items Add Array Items Remove Array Items Sorting Arrays Multidimensional Arrays Array Destructuring Array Spread Operator Search in Arrays Merge Arrays array_map / array_filter / array_reduce Array Functions PHP Superglobals $GLOBALS $_SERVER $_REQUEST $_POST $_GET $_FILES $_COOKIE $_SESSION \$\_ENV PHP RegEx RegEx Patterns RegEx Modifiers preg_match preg_replace preg_split PHP RegEx Functions PHP Form Handling PHP Form Validation PHP Form Required PHP Form URL/E-mail Form Input Sanitizing Escaping Output (htmlspecialchars) Checkbox, Radio and Select Inputs Sticky Forms PHP Form Complete PHP Date and Time Date Formatting DateTime Class Timezones PHP Include Include vs Require PHP File Handling PHP File Open/Read PHP File Create/Write File Delete / Rename / Copy PHP Directories PHP CSV Files PHP File Upload PHP Cookies PHP Sessions PHP Filters PHP Filters Advanced PHP Callback Functions PHP JSON PHP Exceptions Error Handling Custom Error Handler Error Logging HTTP Headers and Redirects Output Buffering Sending Email PHP cURL Consuming REST APIs PHP Generators PHP What is OOP PHP Classes/Objects The $this Keyword PHP Properties PHP Methods PHP Constructor Constructor Property Promotion PHP Destructor PHP Access Modifiers Readonly Properties PHP Inheritance Method Overriding The final Keyword PHP Class Constants PHP Abstract Classes PHP Interfaces Polymorphism PHP Traits PHP Static Methods PHP Static Properties Late Static Binding Magic Methods Object Cloning Comparing Objects Anonymous Classes PHP Enums PHP Namespaces Autoloading Classes PHP Iterables Iterators Object Serialization Strict Types Union Types Nullable Types Mixed and Never Types Nullsafe Operator PHP Attributes PHP Fibers Readonly Classes Property Hooks (PHP 8.4) Asymmetric Visibility (PHP 8.4) Reflection API SPL Data Structures MySQL Database MySQL Connect MySQL Create DB MySQL Create Table MySQL Insert Data MySQL Get Last ID MySQL Insert Multiple MySQL Prepared MySQL Select Data MySQL Where MySQL Order By MySQL Delete Data MySQL Update Data MySQL Limit Data MySQL Joins with PHP Pagination with PHP PDO Introduction PDO Connect PDO Prepared Statements PDO Fetch Modes PDO Transactions PDO Error Handling PHP XML Parsers PHP SimpleXML Parser PHP SimpleXML - Get PHP XML Expat Parser PHP DOM Parser PHP XMLReader PHP XMLWriter AJAX Intro AJAX PHP AJAX Database AJAX XML AJAX Live Search AJAX Poll AJAX with JSON Security Introduction Password Hashing SQL Injection Prevention XSS Prevention CSRF Protection Session Security Secure Cookies File Upload Security Filesystem Security Error Reporting in Production Hiding PHP Encryption with Sodium PHP Configuration (php.ini) PHP Command Line (CLI) Composer PSR-4 Autoloading Installing Extensions (PECL / PIE) Debugging PHP OPcache & Performance Garbage Collection PHP-FPM Migrating to PHP 8 Project: Contact Form with Email Project: Login & Registration System Project: CRUD App with MySQL Project: Image Upload Gallery Project: Shopping Cart with Sessions Project: Simple Blog Project: REST API with PHP
Ask about this post
AI Ask about this post

Ask questions about Spaceship Operator and get answers drawn from it.

Signed-in readers only.