PHP Spaceship Operator <=>

A little known but very useful operator, for example ordered an array list, is the spaceship operator or combined: <=>

It compares two values and returns an entire (-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 this:

An example of use is if you want to sort a array:

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

    $lenB <=> $lenA return;

$values . . .

usort ($values, 'sortByLength');
print_r ($values); Ar[0]ray (>[1] a '> b[2]b '> ccc[3] '> dddd [4]'> fffff '[5]> eeeee)</=>

Leave a Reply