The asort()
function in PHP is used to sort an associative array in ascending order, according to the values, while maintaining the key association (i.e., keys are preserved).
✅ Syntax:
asort(array &$array, int $flags = SORT_REGULAR): bool
&$array
: The input array (passed by reference and modified in place)
flags
: Optional. Specifies the sorting behavior. Common flags:
SORT_REGULAR
– Default: Compare items normally
SORT_NUMERIC
– Compare items numerically
SORT_STRING
– Compare items as strings
SORT_NATURAL
– Compare items using "natural order" (like natsort
)
🔸 Example 1: Basic Usage
$fruits = array("a" => "banana", "b" => "apple", "c" => "mango");
asort($fruits);
print_r($fruits);
Output:
Array
(
[b] => apple
[a] => banana
[c] => mango
)
➡️ Values are sorted, but the keys (a
, b
, c
) remain associated with their original values.
🔸 Example 2: Numeric Array
$numbers = array("x" => 40, "y" => 10, "z" => 100);
asort($numbers);
print_r($numbers);
Output:
Array
(
[y] => 10
[x] => 40
[z] => 100
)
➡️ Sorted by values in ascending order, keys preserved.
🔸 Example 3: With SORT_STRING
$data = array("x" => "20", "y" => "100", "z" => "3");
asort($data, SORT_STRING);
print_r($data);
Output:
Array
(
[y] => 100
[x] => 20
[z] => 3
)
➡️ String-based sorting: "100" comes before "20" and "3".
🔁 Related Functions:
arsort()
– Sort by values in descending order, maintain keys
ksort()
– Sort by keys in ascending order
krsort()
– Sort by keys in descending order
sort()
– Sort by values, reset keys (numeric array)
usort()
– User-defined sort by values