PHP krsort() Function
Topic: PHP Array ReferencePrev|Next
Description
The krsort()
function sorts an associative array in descending order, according to the key.
The keys are preserved, i.e. the key-to-value mapping will remain unchanged by the sort operation.
The following table summarizes the technical details of this function.
Return Value: | Returns TRUE on success or FALSE on failure. |
---|---|
Version: | PHP 4+ |
Syntax
The basic syntax of the krsort()
function is given with:
The following example shows the krsort()
function in action.
Example
Run this code »<?php
// Sample array
$alphabets = array("b"=>"ball", "d"=>"dog", "a"=>"apple", "c"=>"cat");
// Sorting alphabets array
krsort($alphabets);
print_r($alphabets);
?>
Tip: The krsort()
and ksort()
functions used for sorting associative arrays by key, whereas the arsort()
and asort()
functions mainly used for sorting associative arrays by value.
Parameters
The krsort()
function accepts the following parameters.
Parameter | Description |
---|---|
array | Required. Specifies the array to sort. |
sort_flags |
Optional. Specifies how array items should be compared. Possible values are:
|
More Examples
Here're some more examples showing how krsort()
function actually works:
The following example sorts the "persons" associative array by key in descending order:
Example
Run this code »<?php
// Sample array
$persons = array("Harry"=>18, "Clark"=>32, "Peter"=>20, "John"=>24);
// Sorting persons array
krsort($persons);
print_r($persons);
?>