PHP Sort Array Example

Sort arrays by value or key, ascending or descending, and with custom rules. Edit the code below and press Run to execute it with real PHP in your browser.

Code Editor
Output
Ascending: 1, 2, 5, 8, 9
Descending: 9, 8, 5, 2, 1
By age: Ann, Tom, Bob
By name: Ann, Bob, Tom

How this sort array example works

PHP sort functions modify the array in place and return true. sort()/rsort() re-index the array, asort()/arsort() sort by value but keep keys, and ksort()/krsort() sort by key.

Custom sorting with usort() and the spaceship operator

<?php
$people = [["name" => "Ann", "age" => 25], ["name" => "Bob", "age" => 41], ["name" => "Cy", "age" => 33]];
usort($people, fn($a, $b) => $b["age"] <=> $a["age"]);
echo implode(", ", array_column($people, "name"));

Output:

Bob, Cy, Ann