Current Location: Home> Latest Articles> How to Sort PHP Array by Value and Retain Keys

How to Sort PHP Array by Value and Retain Keys

M66 2025-07-15

How to Sort an Array by Value and Retain Keys in PHP

In PHP, the sort() function can be used to sort arrays by value. However, a downside is that it loses the keys of the array. To retain the keys, we can use a custom function.

Custom Sorting Function

Here is a custom function that sorts an array by value while retaining its keys:

function sortByValue($array) {
    $sortedValues = array_values($array);
    asort($sortedValues);
    $sortedKeys = array_keys($sortedValues);
    return array_combine($sortedKeys, $array);
}

Practical Example

Let's assume we have an array with keys. The following code demonstrates how to use the custom function to sort the array:

$array = [
    'apple' => 10,
    'banana' => 20,
    'orange' => 5
];

$sortedArray = sortByValue($array);

print_r($sortedArray);

The output of the above code would be:

Array
(
    [orange] => 5
    [apple] => 10
    [banana] => 20
)

As you can see, the array is sorted in ascending order by value, and the keys remain intact.

Conclusion

With the method outlined in this article, PHP developers can easily sort arrays by value while retaining keys. This approach avoids the key-loss problem that arises when using the sort() function, and is especially useful when maintaining key-value pairs is important.