PHP Function Reference

PHP krsort() Function



The PHP krsort() function is used to sort an array in descending order, according to the key and maintaining key to value association. This is useful mainly for associative arrays.

Syntax

krsort(array, flags)

Parameters

array Required. Specify the array to sort.
flags Optional. Specify sorting type flags to modify the sorting behavior. Sorting type flags:
  • SORT_REGULAR - Default. Compare items normally.
  • SORT_NUMERIC - Compare items numerically.
  • SORT_STRING - Compare items as strings.
  • SORT_LOCALE_STRING - Compare items as strings, based on current locale.
  • SORT_NATURAL - Compare items as strings using natural ordering.
  • SORT_FLAG_CASE - Compare items as strings and case-insensitive. Can be combined (bitwise OR) with SORT_STRING or SORT_NATURAL.

Return Value

Returns true on success and false in failure.

Exceptions

NA.

Example:

In the example below, krsort() function is used to sort an associative array in descending order, according to the key.

<?php
$MyArray = array("Marry"=>25, 
                 "John"=>30, 
                 "Jo"=>45, 
                 "Kim"=>22, 
                 "Adam"=>35);
                 
krsort($MyArray);

print_r($MyArray);
?>

The output of the above code will be:

Array
(
    [Marry] => 25
    [Kim] => 22
    [John] => 30
    [Jo] => 45
    [Adam] => 35
)

Example:

Consider one more example where this function is used to sort an associative array using case-insensitive natural ordering.

<?php
$Arr = array("Color1"=>"Red",
             "color2"=>"Green",
             "Color3"=>"Blue",
             "Color20"=>"White");

krsort($Arr, SORT_NATURAL | SORT_FLAG_CASE);

print_r($Arr);
?>

The output of the above code will be:

Array
(
    [Color20] => White
    [Color3] => Blue
    [color2] => Green
    [Color1] => Red
)

❮ PHP Array Reference