PHP Array Sorting Functions Reference

Choose sorting by key or value, preserve identity and write reliable custom comparison functions.

Lesson 38 of 86Intermediate10 min read

Choosing a PHP sort function requires three decisions: sort by values or keys, ascending or descending, and preserve or replace existing keys. A fourth decision appears when values need a custom rule, such as sorting products by price and then name. Picking a familiar function without checking these choices can detach quantities from their product identifiers.

This reference organizes the functions around those decisions and shows a complete custom comparator. You will also learn why sorting functions modify the supplied array, how equal elements behave in modern PHP, and why display strings should not become your numeric sort keys.

The standard sorting families

sort() orders values ascending and resets numeric keys. rsort() does the same descending. They are appropriate for ordinary lists when original positions are no longer meaningful. Both modify the input array; their return value is not the sorted array. Keep the array variable itself to inspect the result.

asort() sorts values ascending while preserving key-to-value associations, and arsort() sorts values descending with associations preserved. Use them for maps such as product ID to price. The keys remain attached to their values even though iteration order changes. That distinction is critical when a key represents identity.

ksort() and krsort() sort by keys rather than values. They are useful when the identifier or field name determines the desired order. A key sort does not make quantities ascending unless the keys happen to correlate with quantity. State the requested order in plain words before choosing a function.

Comparison flags and natural sorting

Several standard sort functions accept flags such as SORT_NUMERIC, SORT_STRING and SORT_REGULAR. Choose a flag that matches validated input. Mixed numbers, numeric strings and unrelated text can compare in ways that do not reflect the user's expectation. Normalize data before sorting rather than relying on accidental coercion.

Natural sorting treats embedded digit sequences in a human-friendly way, so file2 can come before file10. natsort() preserves keys, and natcasesort() applies case-insensitive natural sorting. Natural order is useful for display names, but it is not the same as locale-aware alphabetical order. For language-specific collation, investigate the appropriate intl facilities.

Do not sort formatted currency strings numerically without returning to validated numeric values. A string containing a currency symbol or thousands separator is presentation data. Keep an integer-cent price or numeric measurement as the sort field, and format only after the order is established.

Custom comparators and the spaceship operator

usort() sorts values using a callback and resets keys. uasort() uses a callback while preserving keys. uksort() compares keys using a callback. A comparator receives two items and returns a negative integer, zero or a positive integer to say which should come first.

The spaceship operator <=> produces that three-way comparison. For ascending prices, return $a['price'] <=> $b['price']. For descending prices, reverse the operands. Add a tie-breaker for a predictable business order, such as comparing names when prices are equal. A comparator must be consistent; contradictory results can make sorting unreliable.

Do not return a boolean such as $a['price'] > $b['price']. It cannot represent all three outcomes correctly, and modern PHP reports diagnostics for inappropriate boolean comparator returns. Do not subtract arbitrary floats and cast the difference to int, because small differences can disappear as zero. The three-way comparison expresses the required contract directly.

Stability and reproducible order

PHP 8's sorting functions preserve the original relative order of elements that compare equal. Earlier versions did not guarantee that stable behavior. A stable sort is useful when a previous meaningful order should survive ties. Still add an explicit tie-breaker when users or pagination need a unique, reproducible order independent of the original input.

Sorting is not the same as filtering. A sort changes order but should not decide which products are visible. Separate those operations so you can test each rule. For large database results, use SQL ORDER BY and a suitable index when possible rather than fetching every row merely to sort in PHP.

The PHP array sorting overview provides a function comparison table and links to detailed contracts. Check key preservation before adapting a code sample: two snippets with the same visible values can leave very different arrays for the next operation.

PHP Array Sorting Functions Reference Examples

Each example shows the code, the output it produces and what each part does.

Example 1

Preserve product IDs when sorting prices

The numeric flag states how values should be compared. Using sort instead would discard these string keys and produce numeric positions. That can be correct for a list of prices, but it would lose the association required to identify the products in this task.

PHP
<?php
$prices = ['bag' => 12, 'pen' => 2, 'book' => 7];
asort($prices, SORT_NUMERIC);
foreach ($prices as $id => $price) {
    echo $id . ':' . $price . PHP_EOL;
}
Output
pen:2
book:7
bag:12
Example 2

Sort records with a tie-breaker

The comparator first checks price. Only a zero result triggers the name comparison. The example uses strcmp for a clear bytewise string order, which is not a complete language-aware collation policy. Validate both fields before sorting external records so the comparator does not need to handle malformed rows.

PHP
<?php
$products = [
    ['name' => 'Book', 'price' => 7],
    ['name' => 'Bag', 'price' => 12],
    ['name' => 'Pen', 'price' => 7],
];
usort($products, function (array $a, array $b): int {
    return ($a['price'] <=> $b['price'])
        ?: strcmp($a['name'], $b['name']);
});
echo implode(',', array_column($products, 'name')) . PHP_EOL;
Output
Book,Pen,Bag

PHP Array Sorting Functions Reference in Real Projects

Practical task: rank a stock map

An inventory screen receives a map from product IDs to counts. Display products with the highest stock first while preserving their IDs. Use a descending value sort with numeric comparison. Then demonstrate that the first key still identifies a product rather than a newly assigned position.

PHP
<?php
$stock = ['pen' => 8, 'book' => 3, 'bag' => 11];
arsort($stock, SORT_NUMERIC);
foreach ($stock as $id => $count) {
    echo $id . '=' . $count . PHP_EOL;
}
Output
bag=11
pen=8
book=3

Arsort fits all three decisions: sort values, descending, preserve keys. Try krsort and explain why the result follows identifier order instead. If equal counts need alphabetical identifier order, write a deliberate compound record comparator or apply a documented stable-sort strategy. Do not assume every tie should be broken the same way in every screen.

PHP Array Sorting Functions Reference FAQ

Why did my array become true?

You probably assigned a sort function's return value back to it. Sorting modifies the supplied array; inspect that array after the call.

Which function keeps associations?

Asort and arsort preserve keys for value sorting; uasort preserves keys with a custom value comparator.

Can I sort nested records?

Yes with usort or uasort and a comparator that reads the intended validated fields.

Why does file10 precede file2 alphabetically?

Bytewise lexical order compares characters. Natural sorting treats digit sequences numerically for a more familiar display order.

Do I need a tie-breaker in PHP 8?

Stability preserves input order, but an explicit tie-breaker is still useful when the final order must be independent of input order.

PHP Array Sorting Functions Reference Exercises

Answer each one and check it instantly. If you get stuck, open the hint before the answer.

Multiple choiceeasy

You need descending quantities with product IDs preserved. Which call fits?

PHP Array Sorting Functions Reference Quiz

2 questions to check what you learned.

  1. Which function sorts values ascending while preserving keys?

    • sort()
    • asort()
    • krsort()
  2. What must a custom comparator return?

    • Only true or false
    • The complete sorted array
    • A negative integer, zero or a positive integer