PHP krsort() Function
In this chapter you will learn:
- Definition for PHP krsort() Function
- Syntax for PHP krsort() Function
- Parameter for PHP krsort() Function
- Note for PHP krsort() Function
- Example - Sort an associative array in descending order, according to the key
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// j a va2s .co 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.
Next chapter...
What you will learn in the next chapter:
- Definition for PHP ksort() Function
- Syntax for PHP ksort() Function
- Parameter for PHP ksort() Function
- Note for PHP ksort() Function
- Example - Pass a second parameter to the sort functions to specify how you want the values sorted
- Example - Sort an associative array in ascending order, according to the key