PHP asort Function
last modified March 13, 2025
The PHP asort function sorts an associative array in ascending
order while maintaining index association. It's useful for sorting arrays
where the key-value relationship is important.
Basic Definition
The asort function sorts an array by its values while keeping
the keys associated with their respective values. It modifies the original
array directly.
Syntax: asort(array &$array, int $flags = SORT_REGULAR): bool.
The function returns true on success, false on failure. The optional flags
parameter modifies sorting behavior.
Basic asort Example
This demonstrates sorting an associative array by values while maintaining key-value pairs.
<?php
$fruits = [
"a" => "orange",
"b" => "banana",
"c" => "apple"
];
asort($fruits);
print_r($fruits);
Output: Array ( [c] => apple [b] => banana [a] => orange ).
The array is sorted alphabetically by values while preserving the keys.
Sorting Numeric Values
asort can sort arrays with numeric values while keeping keys.
<?php
$scores = [
"Alice" => 85,
"Bob" => 92,
"Charlie" => 78
];
asort($scores);
print_r($scores);
Output: Array ( [Charlie] => 78 [Alice] => 85 [Bob] => 92 ).
The scores are sorted from lowest to highest while maintaining name keys.
Using Sorting Flags
The optional second parameter allows specifying different sorting behaviors.
<?php
$mixedNumbers = [
"first" => "10",
"second" => 2,
"third" => "1"
];
asort($mixedNumbers, SORT_NUMERIC);
print_r($mixedNumbers);
Output: Array ( [third] => 1 [second] => 2 [first] => 10 ).
The SORT_NUMERIC flag ensures numeric comparison of values.
Sorting with Custom Comparison
For complex sorting, combine asort with uksort.
<?php
$products = [
"widgetA" => ["price" => 15, "rating" => 4],
"widgetB" => ["price" => 10, "rating" => 5],
"widgetC" => ["price" => 20, "rating" => 3]
];
// Sort by price then rating
uasort($products, function($a, $b) {
return $a["price"] <=> $b["price"] ?: $a["rating"] <=> $b["rating"];
});
print_r($products);
Output shows products sorted first by price, then by rating. The spaceship
operator (<=>) simplifies comparison logic.
Reverse Sorting with arsort
The related arsort function sorts in descending order.
<?php
$ages = [
"John" => 25,
"Mary" => 30,
"Peter" => 20
];
arsort($ages);
print_r($ages);
Output: Array ( [Mary] => 30 [John] => 25 [Peter] => 20 ).
arsort maintains key association while sorting high to low.
Best Practices
- Preserve Keys: Use
asortwhen key-value pairs must remain intact. - Performance: For large arrays, consider sorting flags for optimization.
- Stable Sort: PHP's sort functions are not stable by default.
- Alternative Functions: Consider
ksortfor key-based sorting.
Source
This tutorial covered the PHP asort function with practical
examples showing its usage for sorting associative arrays.
Author
List all PHP Array Functions.