PHP krsort() Function
Definition
The krsort()
function takes an array and reverse sorts it by its
keys while preserving the values.
This is the opposite of the ksort()
.
Syntax
PHP krsort() Function has the following syntax.
bool krsort ( array &arr [, int options] )
Parameter
Parameter | Is Required | Description |
---|---|---|
arr | Required. | Array to sort |
options | Optional. | How to compare the array elements/items. |
Possible values for options:
Value | Description |
---|---|
0 = SORT_REGULAR | Default. Compare items normally without changing types) |
1 = SORT_NUMERIC | Compare items numerically |
2 = SORT_STRING | Compare items as strings |
3 = SORT_LOCALE_STRING | Compare items as strings, based on current locale |
4 = SORT_NATURAL | Compare items as strings using natural ordering |
5 = SORT_FLAG_CASE | an be combined (bitwise OR) with SORT_STRING or SORT_NATURAL to sort strings case-insensitively |
Note
Use the ksort() function to sort an associative array in ascending order, according to the key.
Use the arsort() function to sort an associative array in descending order, according to the value.
<?PHP//w w w . ja va2 s .c o m
$capitalcities['A'] = 'Z';
$capitalcities['B'] = 'X';
$capitalcities['C'] = 'Y';
krsort($capitalcities);
print_r($capitalcities);
?>
krsort()
directly changes the value you pass in.
The return value is either true or false, depending on whether the sorting was successful.
The code above generates the following result.
Example 2
Sort an associative array in descending order, according to the key:
<?php
$age=array("PHP"=>"5","Java"=>"7","java2s.com"=>"9");
krsort($age);
?>
The krsort() function sorts an associative array in descending order, according to the key.