PHP Sort Arrays
PHP has half a dozen sort functions for arrays. The differences come down to: by key or by value? Preserve keys or reindex? Custom comparator?
The matrix
| Function | Sorts by | Keys |
|---|---|---|
sort($arr) | Values ascending | Reindexed 0,1,2… |
rsort($arr) | Values descending | Reindexed |
asort($arr) | Values ascending | Preserved |
arsort($arr) | Values descending | Preserved |
ksort($arr) | Keys ascending | (by definition preserved) |
krsort($arr) | Keys descending | Preserved |
usort($arr, fn($a, $b)) | Custom compare on values | Reindexed |
uasort / uksort | Custom compare | Preserved |
In place
All of these sort the array in place and return true on success. Don't do $arr = sort($arr) — that'd assign true to $arr. Classic bug.
Custom comparator with the spaceship
PHP
$users = [
['name' => 'Ada', 'age' => 36],
['name' => 'Linus', 'age' => 42],
['name' => 'Grace', 'age' => 56],
];
usort($users, fn($a, $b) => $a['age'] <=> $b['age']); // by age asc
usort($users, fn($a, $b) => $b['age'] <=> $a['age']); // by age desc
// Multi-key sort: by age then name
usort($users, fn($a, $b) => [$a['age'], $a['name']] <=> [$b['age'], $b['name']]);
Natural-order sort
PHP
$files = ['img1.png', 'img10.png', 'img2.png']; sort($files); // alphabetical: img1, img10, img2 natsort($files); // natural: img1, img2, img10
Tip: Need a sorted copy without touching the original? Use
array_multisort on a clone, or:
PHP
$sorted = $arr; sort($sorted); // $arr is untouched
Example
Example
<?php $nums = [3, 1, 4, 1, 5]; sort($nums); print_r($nums); // ascending rsort($nums); print_r($nums); // descending $ages = ['Ada' => 36, 'Grace' => 56]; ksort($ages); print_r($ages); // by key asort($ages); print_r($ages); // by valueTry it Yourself »
Exercise
Sort ascending by value, preserving keys.
($ages);
Five letters; starts with a.
Discussion
Loading…