PHP Array Reverse Sorting: This tutorial is covered rsort(), arsort(), and krsort()functions which are used to sort a the values of an array in reverse order.
PHP Array Reverse Sorting: This tutorial is covered rsort(), arsort(), and krsort()functions which are used to sort a the values of an array in reverse order.PHP Array Sort in Reverse Order
In PHP there are three functions are available which are used to sort the values, keys in reverse order. The functions are:
i) rsort()
ii) arsort()
iii) krsort()
i) rsort():
There are several functions are available in PHP, rsort() is one of them, it sorts an array in reverse order, rsort() is just opposite sort() function:
General Format | bool rsort(array $array [,int $sort_flags=SORT_REGULAR] ) | |
Return Value | True/False | |
Parameter | array: the input array
|
sort_flags:
|
Example 3:
<?php
$car=array("manza","safari","nano","vista","jaguar","land rover");
echo "<b>Before sorting the values are:</b>";
print_r($car);
rsort($car);
echo"<br/>";
echo "<b>After sorting values become:</b>";
print_r($car);
?>
Output:
Before sorting the values are:Array ( [0] => manza [1] => safari
[2] => nano [3] => vista [4] => jaguar [5] => land rover )
After sorting values become:Array ( [0] => vista [1] => safari [2]
=> nano [3] => manza [4] => land rover [5] => jaguar )
ii) arsort():
If we consider the name of the function then it will be clear that this function will sort an array in reverse order and maintain index association like asort() + rsort() + sort()=arsort(). Small description of the function is as follows:
General Format | bool arsort(array $array [,int $sort_flags=SORT_REGULAR] ) | |
Return Value | True/False | |
Parameter | array: the input array
|
sort_flags:
|
Example:
<?php
$car=array("m"=>"manza","s"=>"safari","n"=>"nano","v"=>"vista","j"=>"jaguar");
echo "<b>Before sorting the values are:</b>";
print_r($car);
arsort($car);
echo"<br/>";
echo "<b>After sorting values become:</b>";
print_r($car);
?>
Output:
Before sorting the values are:Array ( [m] => manza [s] => safari
[n] => nano [v] => vista [j] => jaguar )
After sorting values become:Array ( [v] => vista [s] => safari [n]
=> nano [m] => manza [j] => jaguar )
iii) krsort(): This function sorts an array by key in reverse order maintaining the correlation with the value, this function is useful for associative array.
General Format | bool krsort(array $array [,int $sort_flags=SORT_REGULAR] ) | |
Return Value | True/False | |
Parameters | array: the input array | sort_flags:
|
Example:
<?php
$array=array(30=>"twitter",11=>"orkut",7=>"facebook");
echo"<b>Before sorting the keys of the array is:</b><br/>";
print_r($array);
krsort($array);
echo"<br/><b>After sorting the keys in reverse order:</b><br/>";
print_r($array);
?>
Output:
Before sorting the keys of the array is:
Array ( [30] => twitter [11] => orkut [7] => facebook )
After sorting the keys in reverse order:
Array ( [30] => twitter [11] => orkut [7] => facebook )