PHP rsort() Function
PHP rsort() Function
The rsort () function in PHP is used to sort an array in reverse order i.e., highest to lowest.
Syntax
rsort ( array &$array [, int $sort_flags = SORT_REGULAR ] )
Parameter
array(required)- This parameter represents the input array.
sort_flags (optional)- This parameter is used to modify the behavior of the sort. The various possible values for sorting type flags are as follows:
- SORT_REGULAR (default) – It is used to compare items normally (don't change types)
- SORT_NUMERIC – This flag is used to compare the items numerically.
- SORT_STRING – It compares the given items as strings.
- SORT_LOCALE_STRING – This flag compares the items as strings, based on the current locale.
- SORT_NATURAL – It is used to compare items as strings using "natural ordering" like natsort().
- SORT_FLAG_CASE – It can be combined (bitwise OR) with SORT_STRING or SORT_NATURAL to sort the given strings case-insensitively
Return
This parameter returns a Boolean value TRUE on success or FALSE on failure.
Example 1
"Reema",2=>"Varun",1=>"Joe",4=>"Ron",3=>"Jai");
//original array
echo("Original array: \n");
print_r($array);
//sorting the array from in reverse order from highest to lowest
rsort($array);
//printing the sorted array
echo("\nSorted array: \n");
print_r($array);
?>
Output
Original array: Array ( [5] => Reema [2] => Varun [1] => Joe [4] => Ron [3] => Jai ) Sorted array: Array ( [0] => Varun [1] => Ron [2] => Reema [3] => Joe [4] => Jai )
Example 2
"Reema", "Age"=>23,"Country"=>"India");
//original array
echo("Original array: \n");
print_r($array);
//sorting the array in reverse order
rsort($array );
//printing the sorted array
echo("\nSorted array without second parameter: \n");
print_r($array);
//sorting array with second parameter as SORT_STRING
rsort($array,SORT_STRING );
//printing the sorted array
echo("\nSorted array with second parameter: \n");
print_r($array);
?>
Output
Original array: Array ( [Name] => Reema [Age] => 23 [Country] => India ) Sorted array without second parameter: Array ( [0] => 23 [1] => Reema [2] => India ) Sorted array with second parameter: Array ( [0] => Reema [1] => India [2] => 23 )
Example 3
array(1 => "mango", 2 => "banana", 2 => "apple"),
"numbers" => array(1, 2, 3, 4, 5, 6),
"values" => array("first", 5 => "second", "third")
);
//sorting the array in reverse order
rsort($array);
//printing the reversed array
print_r($array);
?>
Output
Array ( [0] => Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 [5] => 6 ) [1] => Array ( [0] => first [5] => second [6] => third ) [2] => Array ( [1] => mango [2] => apple ) )
