How to Use asort and arsort in PHP: Sorting Arrays by Value
asort sorts an array by its values in ascending order while keeping the keys linked to their values. Conversely, arsort sorts the array by values in descending order, also preserving key associations.Syntax
asort(array &$array, int $flags = SORT_REGULAR): bool sorts the array by values in ascending order, preserving keys.arsort(array &$array, int $flags = SORT_REGULAR): bool sorts the array by values in descending order, preserving keys.
The $flags parameter controls sorting behavior (like numeric or string sorting) but is optional.
asort(array &$array, int $flags = SORT_REGULAR): bool arsort(array &$array, int $flags = SORT_REGULAR): bool
Example
This example shows how asort sorts an array by values ascending, and arsort sorts descending, both keeping the original keys.
<?php $fruits = ["d" => "lemon", "a" => "orange", "b" => "banana", "c" => "apple"]; // Sort ascending by value, keep keys asort($fruits); print_r($fruits); echo "\n"; // Sort descending by value, keep keys arsort($fruits); print_r($fruits); ?>
Common Pitfalls
One common mistake is expecting asort or arsort to reindex keys; they do not. They preserve keys, so numeric keys remain unchanged. Also, confusing asort with sort can cause unexpected results because sort reindexes keys.
Another pitfall is not understanding the $flags parameter, which affects sorting type (numeric, string, locale).
<?php // Wrong: expecting keys to be reindexed $numbers = [3 => 10, 1 => 2, 2 => 30]; asort($numbers); print_r($numbers); // keys stay 3,1,2 // Right: use sort() if you want keys reindexed $numbers = [3 => 10, 1 => 2, 2 => 30]; sort($numbers); print_r($numbers); // keys become 0,1,2 ?>
Quick Reference
| Function | Sort Order | Preserves Keys | Default Sort Type |
|---|---|---|---|
| asort | Ascending by value | Yes | SORT_REGULAR |
| arsort | Descending by value | Yes | SORT_REGULAR |