ksort: Sorting array by Key |
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.
<?
$input = array ("b" => "Pinaple", "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 -> Pinaple d -> Orange a -> Banana c -> Mango f -> Apple e -> Strawberry
-----After ksort--------- a -> Banana b -> Pinaple c -> Mango d -> Orange e -> Strawberry f -> Apple
|