We can sort an array in reverse order of sort function by using rsort command. Here the index associated with each element is not retained. This is the only difference between rsort and arsort commands.
We can use the array sorting function asort to arrange the array elements alphabetical order. Here by using assort function we can retain or maintain the index association of each element. This can be easily explained by this example. Here is the code and the output is given below that.
We have seen how the elements of data of the array can be sorted by using sort command. Now we will learn how to sort the key part of the array. Each key is associated with a data or element of the array. By using ksort function we can sort the array based on the key order and at the same time associated data link with the key is maintained.
Let us understand this ksort function by this example code.
<?Php
$input = array ("b" => "Pineapple", "d" =>"Orange", "a" =>"Banana", "c" =>"Mango", "f" =>"Apple","e" =>"Strawberry");
while (list ($key, $val) = each ($input)) {
echo "$key -> $val <br>";
}
ksort($input);
echo "<br>-----After ksort---------<br>";
while (list ($key, $val) = each ($input)) {
echo "$key -> $val <br>";
}
?>
Here is the output
b -> Pineapple d -> Orange a -> Banana c -> Mango f -> Apple e -> Strawberry
-----After ksort--------- a -> Banana b -> Pineapple c -> Mango d -> Orange e -> Strawberry f -> Apple
We have seen above how the ksort function sorts the array based on the keys of the element. By using krsort we can just reverse the order of the keys. Here also we have retained the data key association after applying the krsort function.
Let us try with some examples.
<?Php
$input = array ("b" => "Pineapple", "d" =>"Orange", "a" =>"Banana", "c" =>"Mango", "f" =>"Apple","e" =>"Strawberry");
while (list ($key, $val) = each ($input)) {
echo "$key -> $val <br>";
}
krsort($input);
echo "<br>-----After krsort---------<br>";
while (list ($key, $val) = each ($input)) {
echo "$key -> $val <br>";
}
?>
The output of the above code is here
b -> Pineapple d -> Orange a -> Banana c -> Mango f -> Apple e -> Strawberry
-----After krsort--------- f -> Apple e -> Strawberry d -> Orange c -> Mango b -> Pineapple a -> Banana