iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

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

FunctionSorts byKeys
sort($arr)Values ascendingReindexed 0,1,2…
rsort($arr)Values descendingReindexed
asort($arr)Values ascendingPreserved
arsort($arr)Values descendingPreserved
ksort($arr)Keys ascending(by definition preserved)
krsort($arr)Keys descendingPreserved
usort($arr, fn($a, $b))Custom compare on valuesReindexed
uasort / uksortCustom comparePreserved

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 value
Try it Yourself »

Exercise

Sort ascending by value, preserving keys.

($ages);

Test yourself

Q1. sort() returns…
Q2. Preserve keys ascending by value uses…
Q3. For "img1.png, img2.png, img10.png" prefer…

Discussion

Loading…