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
Release: 2024-11-18 05:39:02
Original
681 people have browsed it

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
];
Copy after login

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)
Copy after login

Solution:

array_multisort(array_values($arrTags), SORT_DESC, array_keys($arrTags), SORT_ASC, $arrTags);
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template