Current Location: Home> Latest Articles> How to use krsort sorting with array_flip

How to use krsort sorting with array_flip

gitbox 2025-05-27

1. Function introduction

krsort

krsort is used to reverse sort arrays by keys (keys from large to small). It keeps the correlation between key-value pairs unchanged and is suitable for scenarios where you need to sort by keys.

 $arr = ['a' => 3, 'b' => 1, 'c' => 2];
krsort($arr);
print_r($arr);

The output result is:

 Array
(
    [c] => 2
    [b] => 1
    [a] => 3
)

array_flip

array_flip is used to swap keys and values ​​of an array. The value of the original array will become the key of the new array, and the key will become the value. This is useful when you need to sort by value, or reverse the mapping relationship.

 $arr = ['a' => 3, 'b' => 1, 'c' => 2];
$flipped = array_flip($arr);
print_r($flipped);

Output result:

 Array
(
    [3] => a
    [1] => b
    [2] => c
)

2. Combine krsort and array_flip to complete the sorting

When you need to sort in reverse order based on the values ​​of the array and want to keep the mapping of keys and values ​​of the original array, you can combine array_flip and krsort :

  1. Use array_flip to turn values ​​into keys to facilitate sorting by values.

  2. Use krsort to sort the flipped array in reverse order (i.e., the reverse order of the original array values).

  3. Finally, use array_flip again to restore the keys and values ​​to get the array sorted in reverse order.

Sample code:

 <?php
// Original array
$arr = ['apple' => 5, 'banana' => 3, 'orange' => 8, 'grape' => 2];

// first step:Flip the array,Value becomes key
$flipped = array_flip($arr);

// Step 2:By key(That is, the value of the original array)Sort in reverse order
krsort($flipped);

// Step 3:Flip and restore again,得到Sort in reverse order后的数组
$sorted = array_flip($flipped);

print_r($sorted);

Output result:

 Array
(
    [orange] => 8
    [apple] => 5
    [banana] => 3
    [grape] => 2
)

3. Things to note

  • array_flip requires that the value of the array is unique and can be used as a key (usually a string or an integer), otherwise it will cause data loss.

  • This method is suitable for scenarios sorted by values, and values ​​are unique and suitable as keys.

  • If the value is not unique, using array_flip will overwrite duplicate keys, resulting in inaccurate sorting results.


4. Summary

By combining array_flip and krsort , we can easily implement inverse order sorting according to array values ​​and maintain the key-value correspondence of the original array. This method is simple and efficient, suitable for scenarios with unique values, and is one of the practical techniques for sorting PHP arrays.

For more PHP tips, visit <code> https://gitbox.net/php-tutorials </code>.