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?

FunctionSortsKeeps keys?
sort()Values, low to highNo
rsort()Values, high to lowNo
asort()Values, low to highYes
arsort()Values, high to lowYes
ksort()Keys, low to highYes
krsort()Keys, high to lowYes
usort()Values using your own functionNo
uasort() / uksort()Values / keys using your own functionYes

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
Exercises & Assignments
Remove specific element by value from an array in PHP?
PHP Array to String Conversion (favourite colours chosen by user)
How to check if an array is a subset of another in PHP?
Interview Questions & Answers
What are the different PHP functions to sort an array?
PHP’s numerically indexed array begins with which position?
Which PHP function inserts an element to the end of an array?
Which PHP function can be used check if variable is an array?
How many types of arrays are available in PHP?
What is the use of array_chunk() function in PHP?
What is the use of in_array() function in PHP?