PHP
Sort Associative Array by Value in PHP
Learn how to sort a PHP associative array based on its values, either in ascending or descending order, while maintaining key-value associations.
<?php
$data = [
'apple' => 5,
'banana' => 2,
'orange' => 8,
'grape' => 1
];
// Sort by value in ascending order (a-z, 0-9)
asort($data);
print_r($data);
/* Output:
Array
(
[grape] => 1
[banana] => 2
[apple] => 5
[orange] => 8
)
*/
// Sort by value in descending order (z-a, 9-0)
arsort($data);
print_r($data);
/* Output:
Array
(
[orange] => 8
[apple] => 5
[banana] => 2
[grape] => 1
)
*/
// Custom sort by value using uasort (e.g., sort by string length)
$cities = [
'NYC' => 'New York City',
'LA' => 'Los Angeles',
'CHI' => 'Chicago',
'SF' => 'San Francisco'
];
uasort($cities, function($a, $b) {
return strlen($a) <=> strlen($b);
});
print_r($cities);
/* Output:
Array
(
[CHI] => Chicago
[LA] => Los Angeles
[NYC] => New York City
[SF] => San Francisco
)
*/
?>
How it works: The `asort()` function sorts an associative array in ascending order according to the value, maintaining the key-value association. For descending order, `arsort()` is used. When more complex sorting logic is needed, `uasort()` allows you to define a custom comparison function. This function takes two array values as arguments and should return -1 if the first element is smaller, 1 if larger, or 0 if equal, using the spaceship operator (`<=>`) for brevity.