PHP Arrays and Data Structures

How to Sort Arrays in PHP

Compare PHP sorting functions for values and keys, including indexed, associative, and custom sorting.

How to Sort Arrays in PHP

PHP provides built-in functions for sorting arrays by value or by key. Choosing the right function matters because some sorting functions reindex numeric keys while others preserve key associations.

Sort Indexed Arrays

Use sort() to sort values in ascending order and rsort() for descending order. These functions reindex numeric keys.

$numbers = [8, 2, 5, 1];

sort($numbers);
// [1, 2, 5, 8]

rsort($numbers);
// [8, 5, 2, 1]

For natural, case-insensitive ordering of strings, consider natcasesort().

Sort Associative Arrays by Value

Use asort() to sort values while preserving their key association. Use arsort() for descending value order.

$scores = [
    "Ava" => 91,
    "Noah" => 84,
    "Mia" => 96,
];

arsort($scores);

To sort by keys, use ksort() or krsort().

Custom Sorting

For application-specific rules, use usort(), uasort(), or uksort() with a comparison callback.

$products = [
    ["name" => "Keyboard", "price" => 45],
    ["name" => "Mouse", "price" => 20],
];

usort($products, function (array $a, array $b): int {
    return $a["price"] <=> $b["price"];
});

The spaceship operator (<=>) returns a negative, zero, or positive result according to the comparison.

Important Details

Most sorting functions modify the original array. If the original order is needed later, sort a copy. Be aware of key preservation and string comparison behavior, especially when values contain numbers or mixed character sets.

Conclusion

Use sort() and rsort() for indexed value lists, asort() and arsort() for associative values, and key-sorting functions when keys determine order. Custom callbacks provide control when built-in rules are not enough.

Share this page Help other developers discover this resource.