The way to sort an array by value in PHP while retaining the key names is to use the usort() function to sort the array by value. The usort() function is passed an anonymous function as a comparison function that returns the difference in element values. usort() sorts the array according to an anonymous function while keeping the keys unchanged.
#How to sort an array by value in PHP and preserve key names?
In PHP, you can sort an array by value in ascending order using the asort()
function, or in descending order using the arsort()
function. However, both functions destroy the keys in the array.
If you want to sort the array by value while keeping the key names, you can use the usort()
function as follows:
$arr = array( 'a' => 10, 'b' => 5, 'c' => 20 ); usort($arr, function($a, $b) { return $a - $b; }); print_r($arr);
Output:
Array ( [b] => 5 [a] => 10 [c] => 20 )
In the above code:
usort()
accepts two parameters: the array to be sorted $arr
and an element value used to compare Anonymous function. $a
and $b
and returns their difference. usort()
will sort the elements in the array, using an anonymous function as the comparison function. Practical case
Consider an array containing student grades:
$students = array( 'John' => 90, 'Jane' => 85, 'Peter' => 95 );
You want to sort the student names in ascending order by grade while keeping the name as Key name, you can use the following code:
usort($students, function($a, $b) { return $a - $b; });
Output:
Array ( [Jane] => 85 [John] => 90 [Peter] => 95 )
The above is the detailed content of How to keep key names after sorting PHP array by value?. For more information, please follow other related articles on the PHP Chinese website!