PHP Sorting Arrays
PHP provides several built-in functions to sort arrays in different ways: by value, by key, in ascending or descending order, and while preserving or discarding original keys.
Choosing the right sorting function matters โ for example, sort() reindexes numeric keys, while asort() preserves the key-value associations, which is important for associative arrays.
sort($arr);
asort($arr);
ksort($arr);Sorting indexed arrays
sort() sorts values in ascending order and reindexes keys. rsort() does the same but in descending order.
Sorting associative arrays
asort() sorts by value while keeping keys intact, ksort() sorts by key, and their descending counterparts are arsort() and krsort().
<?php
$nums = [3, 1, 2];
sort($nums);
print_r($nums);
?>Array
(
[0] => 1
[1] => 2
[2] => 3
)sort() rearranges the values in ascending order and resets the keys to 0, 1, 2.
<?php
$ages = ["Ben" => 30, "Amy" => 25];
ksort($ages);
print_r($ages);
?>Array
(
[Amy] => 25
[Ben] => 30
)ksort() sorts the array alphabetically by its keys, keeping key-value pairs together.
Key points
- sort() and rsort() sort indexed arrays and reindex keys.
- asort() and arsort() sort associative arrays by value, preserving keys.
- ksort() and krsort() sort associative arrays by key.
- Choosing the wrong sort function can break key-value relationships.
