Home >Backend Development >PHP Tutorial >How to Sort an Associative Array by Values and Keys in PHP?
Sorting an Associative Array by Values and Keys
PHP offers several functions for sorting arrays. In the case of a flat, associative array where keys are strings, and values are numeric, the array_multisort() function offers a solution for sorting by both values and keys simultaneously.
Example:
Consider the following array:
$arrTags = [ 'mango' => 2, 'orange' => 4, 'apple' => 2, 'banana' => 3 ];
Desired Output:
We aim to sort this array in descending order of values and then in ascending order of keys, resulting in:
orange (4) banana (3) apple (2) mango (2)
Solution:
array_multisort(array_values($arrTags), SORT_DESC, array_keys($arrTags), SORT_ASC, $arrTags);
Explanation:
The above is the detailed content of How to Sort an Associative Array by Values and Keys in PHP?. For more information, please follow other related articles on the PHP Chinese website!