◐ Shell
clean mode source ↗

PHP: rsort - Manual

(PHP 4, PHP 5, PHP 7, PHP 8)

rsortSort 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.

Changelog

Version Description
8.2.0 The return type is true now; previously, it was bool.

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

Found A Problem?

Alex M

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
   }
?>

ray at non-aol dot com

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.