Get "PHP 8 in a Nutshell" (Soon PHP 8.5)
Amit Merchant
Amit Merchant

A blog on PHP, JavaScript, and more

Remembering what spaceship operator do on comparison in PHP

PHP has introduced an operator called “spaceship opearator” (<=>) with the release of PHP7. What this spaceship operator do is compare two expressions i.e. its two operands, let’s say $a and $b, and returns -1, 0 or 1 when $a is respectively less than, equal to, or greater than $b.

Here’s some examples of the same.

<?php
// Integers
echo 1 <=> 1; // 0
echo 1 <=> 2; // -1
echo 2 <=> 1; // 1

// Floats
echo 1.5 <=> 1.5; // 0
echo 1.5 <=> 2.5; // -1
echo 2.5 <=> 1.5; // 1
 
// Strings
echo "a" <=> "a"; // 0
echo "a" <=> "b"; // -1
echo "b" <=> "a"; // 1
?>

The trick

But it turns out a lot of us tend to forget the purpose of the operator more often. So, here’s a handy yet effective trick to remember what this operator do pretty quickly.

What you’d do is to replace the spaceship operator (<=>) with a minus sign (-). If the result is negative, 0 or positive, the expression will return -1, 0 or 1 respectively. As you can see, it’s now more easy to remember when an analogy comes into play.

…And that is also how you remember anything you want, in general.

Coming Soon: PHP 8.5
Learn the fundamentals of PHP 8 (including 8.1, 8.2, 8.3, and 8.4), the latest version of PHP, and how to use it today with my book PHP 8 in a Nutshell. It's a no-fluff and easy-to-digest guide to the latest features and nitty-gritty details of PHP 8. So, if you're looking for a quick and easy way to PHP 8, this is the book for you.

👋 Hi there! This is Amit, again. I write articles about all things web development. If you enjoy my work (the articles, the open-source projects, my general demeanour... anything really), consider leaving a tip & supporting the site. Your support is incredibly appreciated!

Comments?