Home >Backend Development >PHP Tutorial >Sort array by value in PHP using own function, preserving key names
In PHP, the way to sort an array by value and preserve the key name using its own function is to get all the values of the array and sort them. Get the key of the sorted value. Recombine the sorted values with the keys of the original array.
Use your own function in PHP to sort the array by value, retaining the key name
Preface
In PHP, the sort()
function can sort an array by value. However, this function destroys the key names. In order to preserve the key names, we need to use our own function.
Own functions
The following self-owned functions can sort the array by value while retaining the key name:
function sortByValue(array $array) { $sortedValues = array_column($array, null); asort($sortedValues); $sortedKeys = array_keys($sortedValues); return array_combine($sortedKeys, $array); }
Practical case
The following example demonstrates how to sort an array containing key names:
$array = [ 'apple' => 10, 'banana' => 20, 'orange' => 5 ]; $sortedArray = sortByValue($array); print_r($sortedArray);
The output is:
Array ( [orange] => 5 [apple] => 10 [banana] => 20 )
As you can see, the array is sorted by value in ascending order Sorted while preserving key names.
The above is the detailed content of Sort array by value in PHP using own function, preserving key names. For more information, please follow other related articles on the PHP Chinese website!