Code sur écran d'ordinateur

PHP Spaceship Operator <=>

A little-known but very useful operator, for example to sort an array, is the spaceship operator: <=>

It compares two values and returns an integer (-1, 0, 1) depending on the result.

$a < $b returns -1
$a = $b returns 0
$a > $b returns 1

One way to see it is here: https://3v4l.org/WcRSo

Comparing two values with the PHP spaceship operator on 3v4l

An example of use, if you want to sort an array:

function sortByLength($a, $b)
{
    $lenA = strlen($a);
    $lenB = strlen($b);

    return $lenA <=> $lenB;
}

$values = [
    'ccc',
    'a',
    'eeeeee',
    'dddd',
    'bb',
    'fffff'
];

usort($values, 'sortByLength');
print_r($values); //Array ( [0] => a [1] => bb [2] => ccc [3] => dddd [4] => fffff [5] => eeeeee )