🐘 PHP Beginner

What is the spaceship operator in PHP?

Answer

The spaceship operator (<=>), introduced in PHP 7, is a three-way comparison operator that returns -1, 0, or 1 — negative if the left side is less than the right, 0 if equal, positive if greater. It works on integers, floats, strings, arrays, and objects. It is primarily used in sorting callbacks: usort($people, fn($a, $b) => $a["age"] <=> $b["age"]); — this concisely replaces the old pattern of comparing values and returning -1, 0, or 1 manually. For descending sort, swap the operands: $b["age"] <=> $a["age"]. The name "spaceship" comes from the resemblance of <=> to a UFO.