How to Sort an Associative Array by Value in PHP

Sorting an associative array by its values in PHP is a fundamental task that can be accomplished quickly using PHP’s built-in array functions. This article demonstrates how to sort associative arrays in both ascending and descending order while preserving the correlation between the keys and their respective values using the asort() and arsort() functions.

Sorting in Ascending Order: asort()

To sort an associative array by its values in ascending order (lowest to highest) while keeping the original keys intact, use the asort() function.

<?php
$age = array("Peter" => "35", "Ben" => "37", "Joe" => "43", "John" => "25");

// Sort the array by value in ascending order
asort($age);

print_r($age);
?>

Output:

Array
(
    [John] => 25
    [Peter] => 35
    [Ben] => 37
    [Joe] => 43
)

Sorting in Descending Order: arsort()

To sort an associative array by its values in descending order (highest to lowest) while maintaining the key-value association, use the arsort() function.

<?php
$age = array("Peter" => "35", "Ben" => "37", "Joe" => "43", "John" => "25");

// Sort the array by value in descending order
arsort($age);

print_r($age);
?>

Output:

Array
(
    [Joe] => 43
    [Ben] => 37
    [Peter] => 35
    [John] => 25
)

Custom Value Sorting: uasort()

If you need to sort an associative array by value using a custom comparison logic (for example, sorting by string length or complex nested array values), use the uasort() function. This function allows you to define a custom user-defined comparison callback.

<?php
$foods = array("apple" => "banana", "fruit" => "kiwi", "snack" => "pomegranate");

// Sort by the length of the values using a custom callback
uasort($foods, function($a, $b) {
    return strlen($a) <=> strlen($b);
});

print_r($foods);
?>

Output:

Array
(
    [fruit] => kiwi
    [apple] => banana
    [snack] => pomegranate
)