The asort()function in PHP
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
Written by Shaikh Abdul Shahid
A Full-Stack Developer with experience in PHP, Laravel, JavaScript, and React.
Founder of Online Learner, sharing practical knowledge and programming tutorials.
Building and maintaining real-world web applications since 2017.
Your Feedback
Help us improve by sharing your thoughts
Online Learner helps developers master programming, database concepts, interview preparation, and real-world implementation through structured learning paths.
Quick Links
© 2023 - 2026 OnlineLearner.in | All Rights Reserved.
