This is a short PHP tutorial on how to sort array keys in a reverse / descending order. In the examples below, we will sort the keys in a descending order while maintaining the key to element correlations.
Take a look at the following snippet:
//An example PHP array
$fruits = array(
2 => 'Orange',
9 => 'Apple',
3 => 'Banana',
1 => 'Grapes',
4 => 'Mango'
//Use PHP's krsort function to
//sort the array keys in a DESCENDING / Reverse order
//var_dump the array out
In the code above, we created a basic PHP array. As you can see, the keys of this particular array are unordered.
To sort these keys in a descending order so that key 9 is at the top of the array and key 1 is at the bottom of the array, we need to use PHP’s krsort function.
If you run the example above, you will see that the krsort function sorts our array and re-orders it like so:
As you can see, the keys in our array have been sorted in a reverse order. Moreover, each key still correlates to the same element.
Note that krsort does not return the sorted array. Instead, it returns a TRUE or FALSE value, depending on whether the operation has been successful or not. This means that the following piece of code will not work:
//Incorrect way of using krsort.
$fruits = krsort($fruits);
The PHP code above will overwrite our $fruits array with a boolean TRUE variable, which is something that we obviously do not want. krsort does not need to return the sorted array because the original array is passed in as a reference. i.e. The function will modify the array directly.
Hopefully, you found this guide useful!