Sort arrays
| Sort values | |
| Keep keys | |
| Sort with usort | |
| Sort flags |
Sort values
Function sort orders values from low to high and rebuilds numeric keys. Function rsort does the same in reverse order.
Copy the array first when the original order still matters later in the script.
$nums = [3, 1, 2]; sort($nums); print_r($nums);
Keep keys
Associative arrays pair ids with labels, so losing keys breaks the map. Function asort sorts by value while keeping each key with its value.
Function ksort sorts by key instead, which suits configs and menus ordered by name.
$scores = ["bob" => 12, "ann" => 30]; asort($scores); print_r($scores); ksort($scores); print_r($scores);
Sort with usort
Function usort lets you define the order with a callback. Return a negative number when the first item goes first and a positive number when it goes second.
The spaceship operator keeps the callback to one line and handles numbers and strings cleanly.
$users = [["name" => "Bob", "age" => 30], ["name" => "Ann", "age" => 25]]; usort($users, fn($a, $b) => $a["age"] <=> $b["age"]); print_r($users);
Sort flags
Sort flags tune how values compare. Numeric mode treats strings as numbers while natural mode orders embedded numbers like a human would.
Use case-insensitive string mode for names so lowercase and uppercase mix evenly.
$files = ["img10", "img2", "img1"]; sort($files, SORT_NATURAL); print_r($files); $names = ["bob", "Ann"]; sort($names, SORT_FLAG_CASE | SORT_STRING); print_r($names);
Next: DateTimeImmutable deep dive
Article author: Arthur Isaev