Home >Backend Development >PHP Tutorial >How to Sort an Associative Array by Values and Keys in PHP?

How to Sort an Associative Array by Values and Keys in PHP?

Susan Sarandon
Susan SarandonOriginal
2024-11-18 05:39:02694browse

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:

  • array_values($arrTags) extracts the values as a separate array.
  • SORT_DESC specifies descending order for values.
  • array_keys($arrTags) extracts the keys as a separate array.
  • SORT_ASC specifies ascending order for keys.
  • Finally, the sorted values and keys are merged back into the original array using $arrTags.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn