Advertisement
Intermediate PHP, Basics & Types

What are PHP's comparison operators, and how does the spaceship operator introduced in PHP 7 simplify writing custom comparison logic?

Short answer

PHP provides standard comparison operators like equal to, not equal to, greater than, and less than, along with the spaceship operator, which compares two values and returns negative one, zero, or one depending on whether the first value is less than, equal to, or greater than…

Save PHP mock interview
Advertisement
AModel answer
PHP provides standard comparison operators like equal to, not equal to, greater than, and less than, along with the spaceship operator, which compares two values and returns negative one, zero, or one depending on whether the first value is less than, equal to, or greater than the second, making it especially convenient for writing concise custom sorting logic within functions like usort.
$result = 5 <=> 3;
echo $result;

usort($numbers, fn($a, $b) => $a <=> $b);
Real-world example
A sorting function for a leaderboard uses the spaceship operator within a custom comparison callback to sort players by score, expressing the comparison logic in a single, clear line rather than a multi line if else structure.
Likely follow-ups
  • What does the spaceship operator return for equal values?
  • How does the spaceship operator behave when comparing arrays or objects?
Related topics