The array function used for arrangement of elements in ascending ,descending (lower to higher) and alphabetical or numerical order. In the Php has several functions are used for sorting the array.
There are many sorting methods in PHP are followings.
sort() :- Sort function is used for arrangement of array in ascending order. Example :-
There are many sorting methods in PHP are followings.
sort() :- Sort function is used for arrangement of array in ascending order. Example :-
<?php $name = array("Rahul", "Mukesh", "Sonu"); sort($name); $nlength = count($name); for($x = 0; $x < $nlength; $x++) { echo $name[$x] ."<br>" ; } ?>
Output:-
Mukesh Rahul Sonu
rsort() :- Rsort function is used for arrangement of array in descending order
Example :-
<?php $name = array("Rahul", "Mukesh", "Sonu"); rsort($name); $nlength = count($name); for($x = 0; $x < $nlength; $x++) { echo $name[$x] . "<br>" ; } ?>
Output:-
Sonu Rahul Mukesh
asort() :- Asort function is used for sorting the array in ascending order and maintain the index of each array.
Example :-
<?php$colors = array("b" => "red", "c" => "orange", "a" => "blue", "d" => "green"); asort($colors); foreach ($colors as $key => $col) { echo "$key = $col \n"; } ?> Output :- a = blue d = green c = orange b = red
ksort() :- Ksort function is used for sorting the array in ascending order according to key of the element. Example :-
<?php $colors = array("b" => "red", "c" => "orange", "a" => "blue", "d" => "green"); ksort($colors); foreach ($colors as $key => $col) { echo "$key = $col \n"; } ?> Output :-
a = blue b = red c = orange d = green
arsort() :- Arsort function is used for sorting the array in descending order and according to value of array elements. Example :- <?php $colors = array("b" => "red", "c" => "orange", "a" => "blue", "d" => "green"); arsort($colors); foreach ($colors as $key => $col) { echo "$key = $col \n"; } ?> Output :- b = red c = orange d = green a = blue
krsort() :- Krsort function is used for sorting the array in descending order and according to key of array elements. Example :- <?php$colors = array("b" => "red", "c" => "orange", "a" => "blue", "d" => "green"); krsort($colors); foreach ($colors as $key => $col) { echo "$key = $col \n"; } ?> Output :-d = green c = orange b = red a = blue