Last updated: August 26, 2026.
Choose a PHP sorting function based on whether you are sorting values or keys and whether key associations must be preserved. The functions sort the array in place.
| Function | Sorts | Preserves key association |
|---|---|---|
sort() / rsort() | Values ascending/descending | No; numeric keys are reassigned |
asort() / arsort() | Values ascending/descending | Yes |
ksort() / krsort() | Keys ascending/descending | Yes |
usort() / uasort() | Values with a callback | uasort only |
Common examples
<?php
$names = ['file20', 'File3', 'file1'];
sort($names, SORT_NATURAL | SORT_FLAG_CASE);
$prices = ['basic' => 20, 'pro' => 50, 'team' => 35];
asort($prices, SORT_NUMERIC);
$users = [
['name' => 'Mina', 'score' => 84],
['name' => 'Alex', 'score' => 92],
];
usort($users, static fn(array $a, array $b): int => $b['score'] <=> $a['score']);sort() discards existing numeric keys, while asort() preserves associations. Avoid mixed data types unless the comparison rule is explicit. See PHP’s sorting-function comparison.