0
0
PhpHow-ToBeginner · 3 min read

How to Use asort and arsort in PHP: Sorting Arrays by Value

In PHP, 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.

php
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
<?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);
?>
Output
Array ( [c] => apple [b] => banana [d] => lemon [a] => orange ) Array ( [a] => orange [d] => lemon [b] => banana [c] => apple )
⚠️

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
<?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
?>
Output
Array ( [1] => 2 [3] => 10 [2] => 30 ) Array ( [0] => 2 [1] => 10 [2] => 30 )
📊

Quick Reference

FunctionSort OrderPreserves KeysDefault Sort Type
asortAscending by valueYesSORT_REGULAR
arsortDescending by valueYesSORT_REGULAR

Key Takeaways

Use asort to sort arrays by values ascending while keeping keys intact.
Use arsort to sort arrays by values descending while preserving keys.
asort and arsort do not reindex keys; use sort if you want reindexed keys.
The optional flags parameter controls sorting type like numeric or string.
Remember to choose the right function based on whether you want ascending or descending order.