W3docs

sort()

Sorting arrays is a crucial task in PHP programming that helps in organizing data in a specific order. This article aims to explain the different methods of

Introduction

Sorting is one of the most common things you do with arrays: ordering a price list, alphabetizing names, ranking scores. PHP ships with a whole family of sorting functions, and the one you reach for depends on two questions — sort by value or by key? and do you need to keep the original keys?

This chapter explains sort() and its relatives, shows the output of each one, and helps you pick the right function the first time.

Understanding PHP Array Sorting

PHP's array-sort functions modify the array in place (by reference) and return true on success or false on failure — they do not return a new sorted array. So you always write sort($arr);, never $arr = sort($arr);.

The functions fall into a predictable naming pattern:

FunctionSorts byKeeps key associations?Order
sort()valueNo (reindexes 0,1,2…)ascending
rsort()valueNodescending
asort()valueYesascending
arsort()valueYesdescending
ksort()keyYesascending
krsort()keyYesdescending
usort()custom (value)Nocustom
uasort()custom (value)Yescustom
uksort()custom (key)Yescustom

The pattern is easy to read once you know it: a leading a means "keep key Associations", a k means "sort by Key", an r means "Reverse", and a u means "User-defined comparison".

sort()

The sort() function sorts an array in ascending order by value. It is the right choice for plain indexed (list-style) arrays where you don't care about the original keys — and that's the catch: sort() throws away the existing keys and reindexes from 0. Never use it on an associative array you want to keep intact.

$numbers = [3, 1, 2];
sort($numbers);
print_r($numbers);

Output:

Array
(
    [0] => 1
    [1] => 2
    [2] => 3
)

It works on strings too, comparing them alphabetically:

$fruits = ["banana", "apple", "cherry"];
sort($fruits);
print_r($fruits);
// Array ( [0] => apple [1] => banana [2] => cherry )

You can override the comparison rule with the optional second flags argument — for example SORT_NUMERIC, SORT_STRING, or SORT_NATURAL (which sorts "img10" after "img2" the way a human would).

asort()

The asort() function sorts by value in ascending order but preserves the key-value pairing. Use it when the keys carry meaning — like a map of names to scores.

$scores = ['Alice' => 85, 'Bob' => 92, 'Charlie' => 78];
asort($scores);
print_r($scores);

Output (rows are reordered, but each name keeps its score):

Array
(
    [Charlie] => 78
    [Alice] => 85
    [Bob] => 92
)

Compare this with sort($scores), which would have replaced Charlie/Alice/Bob with 0/1/2 and lost the names entirely.

ksort()

The ksort() function sorts an array by its keys in ascending order, keeping each key with its value. This is handy when keys are IDs, dates, or labels you want in order.

$data = ['c' => 3, 'a' => 1, 'b' => 2];
ksort($data);
print_r($data);

Output:

Array
(
    [a] => 1
    [b] => 2
    [c] => 3
)

usort() and uasort()

When the built-in orderings aren't enough — sorting objects, sorting by a nested field, or applying business rules — pass your own comparison function. usort() sorts a regular array (reindexing keys), while uasort() does the same but preserves keys.

The comparison callback receives two elements and must return an integer: negative if the first should come before the second, positive if after, and zero if they are equal. The spaceship operator <=> returns exactly that, so it's the idiomatic choice.

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

usort($people, function ($a, $b) {
    return $a['age'] <=> $b['age']; // sort by age, ascending
});

foreach ($people as $p) {
    echo $p['name'] . ": " . $p['age'] . "\n";
}

Output:

Bob: 25
Alice: 30
Carol: 35

To sort descending, swap the operands: return $b['age'] <=> $a['age'];.

Descending Order

For simple reverse ordering, use the r-prefixed variants instead of writing a custom callback: rsort() (by value, reindexes), arsort() (by value, keeps keys), and krsort() (by key, keeps keys).

$numbers = [3, 1, 2];
rsort($numbers);
print_r($numbers);
// Array ( [0] => 3 [1] => 2 [2] => 1 )

If you need "human-friendly" alphanumeric ordering, look at natsort(), which sorts ["img12", "img2"] as img2, img12 rather than the strict ASCII order img12, img2.

Practical Applications of PHP Array Sorting

Sorting arrays in PHP has various practical applications, including:

Sorting Arrays of Product Prices

When building an e-commerce website, you may need to sort products based on their prices. Using PHP array sorting functions, you can sort an array of product prices in ascending or descending order, allowing customers to filter products by price range.

Sorting Arrays of Database Records

When retrieving data from a database, you may need to sort the records based on specific criteria, such as date, time, or alphabetical order. Using PHP array sorting functions, you can sort the database records after retrieving them, making it easier to analyze the data.

Sorting Arrays of User Input

When collecting data from user input, you may need to sort the data based on specific criteria, such as age or location. Using PHP array sorting functions, you can sort the user input data in ascending or descending order, making it easier to display the data to other users.

Conclusion

Choosing the right sort comes down to two questions: are you ordering by value or by key, and do you need to keep the original keys? Use sort()/rsort() for plain lists, asort()/arsort() and ksort()/krsort() when keys matter, and usort()/uasort() when you need custom rules. Because all of these sort in place and return a boolean, remember to call them as statements — not to assign their result back to the array.

Practice

Practice
Which of these are correct ways to sort an array in PHP?
Which of these are correct ways to sort an array in PHP?
Was this page helpful?