Chaining Spaceship¶
<?php
function foo($a, $b) {
return $a[0] <=> $b[0] ?:
$a[1] <=> $b[1] ?:
$a[2] <=> $b[2] ?:
0;
}
$array = [
[1, 2, 3],
[1, 3, 5],
[1, 2, 4],
[0, 2, 3],
];
usort($array, foo(...));
print_r($array);
It is possible to chain several spaceship operations by using the coalesce operator ?:. When the first spaceship operator returns 1 or -1, its value is immediately used. On the other hand, when the operation leads to 0, the coalesce ?: uses the else branch, where the second spaceship operator is used, to the same effect.
This expression here replaces a call to array_multi_sort().
And of course, literally chaining spaceships together is a very bad idea.
See Also¶
PHP Features¶
Last updated: 14 July 2026