In this PHP tutorial, we will show you how to sort array keys in a reverse / descending order.
In the examples below, we will sort the keys in descending order while maintaining the key-to-value 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 krsort($fruits); //var_dump the array out var_dump($fruits);
In the example 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 will need to use the 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 are now in reverse order. Furthermore, each key still correlates to the same element.
Please 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 to happen.
krsort does not need to return the sorted array because the original array is passed in as a reference. This basically means that the function will modify the array directly.