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 normallySORT_NUMERIC
– Compare items numericallySORT_STRING
– Compare items as stringsSORT_NATURAL
– Compare items using "natural order" (likenatsort
)
🔸 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 keysksort()
– Sort by keys in ascending orderkrsort()
– Sort by keys in descending ordersort()
– Sort by values, reset keys (numeric array)usort()
– User-defined sort by values
At Online Learner, we're on a mission to ignite a passion for learning and empower individuals to reach their full potential. Founded by a team of dedicated educators and industry experts, our platform is designed to provide accessible and engaging educational resources for learners of all ages and backgrounds.
Copyright 2023-2025 © All rights reserved.