What are the different PHP functions to sort an array?
PHP has many functions to sort an array. Choose one by asking: do you sort by value or by key, in which order, and do you need to keep the keys?
| Function | Sorts | Keeps keys? |
|---|---|---|
| sort() | Values, low to high | No |
| rsort() | Values, high to low | No |
| asort() | Values, low to high | Yes |
| arsort() | Values, high to low | Yes |
| ksort() | Keys, low to high | Yes |
| krsort() | Keys, high to low | Yes |
| usort() | Values using your own function | No |
| uasort() / uksort() | Values / keys using your own function | Yes |
For text with numbers like “img2” and “img10”, natsort() gives a natural order. Here is a custom sort with usort().
<?php
$people = [["Anil", 30], ["Robin", 25], ["Zoya", 22]];
usort($people, fn($a, $b) => $a[1] <=> $b[1]); // by age
echo $people[0][0];
?>
Output:
Tutorials Class - Output Window
Zoya
See more examples in PHP Array Functions and ksort().
Learn more about the similar topics:
| Tutorials |
|---|
| PHP Arrays |
| PHP Array Functions |