PHP: rsort - Manual
(PHP 4, PHP 5, PHP 7, PHP 8)
rsort — Sort an array in descending order
Description
Note: If two members compare as equal, they retain their original order. Prior to PHP 8.0.0, their relative order in the sorted array was undefined.
Note: This function assigns new keys to the elements in
array. It will remove any existing keys that may have been assigned, rather than just reordering the keys.
Note: Resets array's internal pointer to the first element.
Return Values
Always returns true.
Examples
Example #1 rsort() example
<?php
$fruits = array("lemon", "orange", "banana", "apple");
rsort($fruits);
foreach ($fruits as $key => $val) {
echo "$key = $val\n";
}
?>The above example will output:
0 = orange 1 = lemon 2 = banana 3 = apple
The fruits have been sorted in reverse alphabetical order.
See Also
- sort() - Sort an array in ascending order
- arsort() - Sort an array in descending order and maintain index association
- krsort() - Sort an array by key in descending order
- The comparison of array sorting functions
Found A Problem?
21 years ago
A cleaner (I think) way to sort a list of files into reversed order based on their modification date.
<?php
$path = $_SERVER[DOCUMENT_ROOT]."/files/";
$dh = @opendir($path);
while (false !== ($file=readdir($dh)))
{
if (substr($file,0,1)!=".")
$files[]=array(filemtime($path.$file),$file); #2-D array
}
closedir($dh);
if ($files)
{
rsort($files); #sorts by filemtime
#done! Show the files sorted by modification date
foreach ($files as $file)
echo "$file[0] $file[1]<br>\n"; #file[0]=Unix timestamp; file[1]=filename
}
?>21 years ago
Like sort(), rsort() assigns new keys for the elements in array. It will remove any existing keys you may have assigned, rather than just reordering the keys. This means that it will destroy associative keys.
$animals = array("dog"=>"large", "cat"=>"medium", "mouse"=>"small");
print_r($animals);
//Array ( [dog] => large [cat] => medium [mouse] => small )
rsort($animals);
print_r($animals);
//Array ( [0] => small [1] => medium [2] => large )
Use KSORT() or KRSORT() to preserve associative keys.