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

Publicités

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

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 . . .
    'ccc',
    'a',
    'eeeeee',
    'dddd',
    'bb',
    'fffff'
];

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

Leave a Reply