Home >Backend Development >PHP Tutorial >How to Sort an Associative Array by Numeric Value and Key Alphabetically?
Sorting Arrays by Numeric Values and Keys
In programming, situations arise where we need to sort associative arrays by specific criteria. One such scenario is sorting an array by numeric values and then by keys.
Suppose we have an array containing string keys and numeric values representing tag occurrences:
$arrTags = [ 'mango' => 2, 'orange' => 4, 'apple' => 2, 'banana' => 3 ];
Our goal is to display the tags in a list with the highest occurrence first, and in case of equal occurrences, sort the tag names alphabetically. This would result in:
orange (4) banana (3) apple (2) mango (2)
While the arsort() function can initially sort the values, it will fail to maintain the alphabetical order of keys when multiple values are equal.
As suggested by Scott Saunders, we can utilize the array_keys() and array_values() functions to overcome this limitation:
array_multisort(array_values($arrTags), SORT_DESC, array_keys($arrTags), SORT_ASC, $arrTags);
This combination of functions allows us to directly manipulate the array's keys and values, ultimately achieving the desired sorting behavior. By sorting the values in descending order and then sorting the keys in ascending order, we obtain our desired output.
The above is the detailed content of How to Sort an Associative Array by Numeric Value and Key Alphabetically?. For more information, please follow other related articles on the PHP Chinese website!