Skip to main content
The <=> (spaceship) operator, formally known as the three-way comparison operator, evaluates two expressions and returns an integer representing their relative order. Introduced in PHP 7.0, it performs a combined less-than, equal-to, and greater-than comparison in a single operation.

Return Value Mechanics

The operator evaluates the operands and strictly returns one of three integer values:
  • 0 if $expr1 is equal to $expr2 ($expr1 == $expr2)
  • -1 if $expr1 is less than $expr2 ($expr1 < $expr2)
  • 1 if $expr1 is greater than $expr2 ($expr1 > $expr2)

Evaluation Rules and Type Coercion

The <=> operator relies on PHP’s standard loose comparison rules. It does not perform strict type checking (like ===); instead, it applies type coercion when comparing operands of different data types. Associativity: The operator is non-associative. Chaining the operator (e.g., $a <=> $b <=> $c) will result in a fatal parse error.

Syntax Visualization by Data Type

Integers and Floats Numeric comparison is evaluated by standard mathematical value.
Strings Strings are evaluated using lexicographical order based on their ASCII/byte values. Case sensitivity applies, with uppercase letters having lower ASCII values than lowercase letters.
Mixed Types (Strings and Numbers) When comparing a string to a number, PHP’s behavior depends on the string’s contents and the PHP version. In PHP 8.0 and later (“Saner string to number comparisons”), if the string is non-numeric, the number is cast to a string and compared lexicographically.
Booleans Boolean comparison treats false as less than true.
Null null evaluates as equal to null, false, and empty strings (""), following standard type juggling rules.
Arrays Array comparison evaluates sequentially: it first compares the count of elements, then the keys, and finally the values element by element.
Objects When comparing objects of the same class, the operator recursively compares their properties based on the order they were declared.
Tired of Poor PHP Skills? Fix That With Deep Grasping!Learn More