PHP krsort is an inbuilt Function in PHP. It sorts arrays in descending order according to keys while maintaining the relationship between keys and values. The smallest key in the input array appears last and the largest appears first. In this article, we will discuss the PHP krsort Function. Also, we will discuss a few examples of using it.
In order to sort an array in ascending order by key, you can use PHP ksort Function.
bool krsort( $array, $sortingType = SORT_REGULAR )
The PHP krsort Function expects two parameters. However, only the first parameter is mandatory.
- $array: The first parameter to the function is an array which you need to sort by key. Also, it is a mandatory parameter.
- $sortingType: The function provides sorting types which are optional to pass. This parameter can take the following values:
- SORT_REGULAR: On passing SORT_REGULAR or 0, the function compares the elements normally without changing their type. Also, this is the default value to the parameter.
- SORT_NUMERIC: On passing SORT_NUMERIC or 1, the function compares the elements numerically.
- SORT_STRING: The function compares the elements string-wise on passing SORT_STRING or 2.
- SORT_LOCALE_STRING: The function compares the elements as a string based on current locale on passing SORT_LOCALE_STRING or 3. It uses the locale which can be changed by the setlocale function.
The PHP krsort Function returns true on success and false on failure. However, it modifies the original input array by soring it in descending order on keys.
Note: The function preserves the keys of the original array after sorting. Also, if two values are equal, their relative order in the sorted array is undefined.
Let’s discuss a few examples of using the krsort Function in PHP.
Example 1: Sort Integer Array in Descending Order By Keys
<?php $testArray = array(1 => 5, 0 => 6, 4 => 3, 3 => 2, 2 => 1); krsort($testArray); print_r($testArray); /* Array (  => 3  => 2  => 1  => 5  => 6 ) */ ?>
You should observe that the function sorts the array on keys in descending order.
Example 2: Sorting String Keys
Similarly, you can also sort an array having string keys.
<?php $testArray = array("z" => 1, "y" => 2, "x" => 3, "n" => 4, "o" => 5, "b" => 6); krsort($testArray); print_r($testArray); /* Array ( [z] => 1 [y] => 2 [x] => 3 [o] => 5 [n] => 4 [b] => 6 ) */ ?>
In conclusion, we discussed the PHP krsort Function in this article. It sorts an array in descending order on the basis of keys. You can read more about it on the Official PHP Documentation. Also, you can learn about more PHP Array Functions on Concatly.
Vishesh is currently working as a Lead Software Engineer at Naukri.com. He passed out of Delhi College of Engineering in 2016 and likes to play Foosball. He loves traveling and is an exercise freak. His expertise includes Java, PHP, Python, Databases, Design and Architecture.