PHP Sorting Arrays

PHP Sorting Arrays

PHP has a comprehensive set of built-in functions to sort arrays in various ways.

1 - sort() and rsort() — Indexed

$nums = [4, 2, 8, 1, 5];
sort($nums);   // [1, 2, 4, 5, 8] — ascending
rsort($nums);  // [8, 5, 4, 2, 1] — descending

2 - asort() / arsort() — Associative (by value)

$scores = ["Alice" => 85, "Bob" => 92, "Carol" => 78];
asort($scores);
// Carol: 78, Alice: 85, Bob: 92 — keys preserved

3 - ksort() / krsort() — Sort by Key

$data = ["b" => 2, "a" => 1, "c" => 3];
ksort($data);  // a:1, b:2, c:3

4 - usort() — Custom Comparator

$people = [
    ["name" => "Bob",   "age" => 30],
    ["name" => "Alice", "age" => 25],
    ["name" => "Carol", "age" => 35],
];

usort($people, fn($a, $b) => $a["age"] - $b["age"]);
// Alice (25), Bob (30), Carol (35)

5 - Sorting Objects

$products = [/* array of Product objects */];

usort($products, fn($a, $b) => strcmp($a->name, $b->name));

Note: All sorting functions modify the array in place and return true on success — they do NOT return a new sorted array. Reference the original variable after sorting.

-Tip-