Syntax
usort($rows, fn($a, $b) => $a["rank"] <=> $b["rank"]);Examples
PHP usort record ordering
Run as a PHP 8.0+ CLI script, for example php example.php. The multibyte example additionally requires mbstring.
<?php
$rows = [['name' => 'Lin', 'rank' => 2], ['name' => 'Ada', 'rank' => 1]];
usort($rows, fn(array $a, array $b): int => $a['rank'] <=> $b['rank']);
echo implode(',', array_column($rows, 'name')), PHP_EOL;- Output: Ada,Lin. The spaceship operator returns a negative value, zero or a positive value as required by the comparator.
Best practices
- Return an integer comparison result, not a boolean. Use uasort when key associations must be preserved.
Runtime & versions
PHP runtime on a server or CLI. Feature availability depends on the language and runtime version used by your project; consult the official reference below.
PHP Manual