宇宙船演算子は、
複数の軸をまたがった複合的な値を明快に比較する用途に使えます。
以下の例は、$people
を last name で比較し、
それが一致するものについては first name で比較します。
<?php
$people[0] = ['first' => 'Adam', 'last' => 'West'];
$people[1] = ['first' => 'Alec', 'last' => 'Baldwin'];
$people[2] = ['first' => 'Adam', 'last' => 'Baldwin'];
function sorter(array $a, array $b) {
return [$a['last'], $a['first']] <=> [$b['last'], $b['first']];
}
usort($people, 'sorter');
foreach ($people as $person) {
print $person['last'] . ', ' . $person['first'] . PHP_EOL;
}
?>
Baldwin, Adam
Baldwin, Alec
West, Adam