PHP 7 introduced two new ways to perform comparisons to add to those already supported by the language. These new comparison operators greatly reduce the amount of code needed to perform a couple of very common tasks.
Let's begin by considering a very common statement indeed - the one that tests if a value has been passed into the code and if it has validates it and if it hasn't substitutes a default value.
$username = isset($_GET['user']) ? validateUser($_GET['user']) : 'nobody';
The null coalesce operator provides us with a way of making this code shorter although it does mean that we end up having to pass the default value through the validation function rather than simply being able to assume that it is valid (which is not necessarily a bad thing anyway).
$username = validateUser($_GET['user'] ?? 'nobody');
We get an even greater saving if we are going to check both the $_GET and corresponding $_POST fields.
$username = validateUser($_GET['user'] ?? $_POST['user'] ?? 'nobody');
The second new comparison operator is being called the spaceship operator because <=> looks a bit like a spaceship. This operator compares the values on either side but doesn't return true/false. Instead it returns -1/0/1 depending on whether the values are equal or when not equal as to which one is the greater. It can compare not only integers and floats but also strings where the values are considered to have their normal PHP sort order. This operator basically combines two comparisons into one. Instead of first needing to compare for less than and then comparing for greater than it does both in a single command. Instead of having the two comparisons:
$a = ($b > $c) ? -1 : ($b < $c) ? 1 : 0;
We can now reduce that to a much shorter statement:
$a = $b <=> $c;
Neither of these new comparison operators actually adds anything new into PHP in that each is simply providing a shorter way of specifying what would otherwise be a slightly longer command. Perhaps the most useful aspect of these new comparisons is the way that they make the code that uses them more readable.
This article written by Stephen Chapman, Felgall Pty Ltd.