Last active
April 30, 2025 09:19
-
-
Save MarcinGladkowski/e612fae8da2c066770139471a4183bf8 to your computer and use it in GitHub Desktop.
PHP callback usort by multiple properties
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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