Skip to content

Instantly share code, notes, and snippets.

@MarcinGladkowski
Last active April 30, 2025 09:19
Show Gist options
  • Save MarcinGladkowski/e612fae8da2c066770139471a4183bf8 to your computer and use it in GitHub Desktop.
Save MarcinGladkowski/e612fae8da2c066770139471a4183bf8 to your computer and use it in GitHub Desktop.
PHP callback usort by multiple properties
<?php
class User
{
public function __construct(
public string $id,
public int $score
) {
}
}
// sort by score, then by id
$users = [
new User('c', 3),
new User('e', 1),
new User('a', 1),
new User('b', 1),
];
uasort($users, function ($a, $b) {
return $a->score <=> $b->score ?: $a->id <=> $b->id;
});
foreach ($users as $user) {
echo sprintf("%s(%d)", $user->id, $user->score) . PHP_EOL;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment