PHP sorting, usort, and the spaceship operator

sort and rsort order the values of an array and renumber the keys, while asort, arsort, ksort, and krsort keep the key–value pairs. Since PHP 8.0 the sorts are stable, so equal elements keep their original order. By default strings are compared as strings with capital letters first, so "Fig" sorts before "apple". The flag SORT_FLAG_CASE | SORT_STRING ignores the case.

PHP
<?php
$numbers = [5, 2, 9, 1, 5, 6];
sort($numbers);
echo implode(" ", $numbers), "\n";
rsort($numbers);
echo implode(" ", $numbers), "\n";

$people = [["Ada", 30], ["Bo", 25], ["Cy", 30], ["Di", 25]];
usort($people, fn($a, $b) => $a[1] <=> $b[1] ?: strcmp($a[0], $b[0]));
echo implode(",", array_column($people, 0)), "\n";

$words = ["pear", "apple", "Fig"];
sort($words);
echo implode(",", $words), "\n";
sort($words, SORT_FLAG_CASE | SORT_STRING);
echo implode(",", $words), "\n";

$scores = ["Ada" => 90, "Bo" => 85, "Cy" => 90];
arsort($scores);
echo implode(",", array_keys($scores)), "\n";
Read the full lesson