In PHP there are some sorting function .These function are used to sort the array.
sort() :
This function is used to sort in ascending alphabetical order.
<?php
$mobile = array("Samsung", "Nokia", "Micromax");
sort($mobile); $length = count($mobile);
for($a = 0; $a < $length; $a++) {
echo $mobile[$a];
echo "<br>";
}
?>
rsort():
This function is used to sort in descending alphabetical order.
<?php
$mobile = array("Samsung", "Nokia", "Micromax");
rsort($mobile);
$length = count($mobile);
for($a = 0; $a < $length; $a++) {
echo $mobile[$a];
echo "<br>";
}
?>
asort():
Sort an associative array in ascending order, according to the value.
<?php
$salary = array("Neha"=>"35000", "Shikha"=>"45000", "Ravi"=>"40000");
asort($salary);
foreach($salary as $a => $a_value) {
echo "Key=" . $a . ", Value=" . $a_value;
echo "<br>";
}
?>
ksort():
Sort an associative array in ascending order, according to the key.
<?php
$salary = array("Shikha"=>"45000", "Neha"=>"35000", "Ravi"=>"40000");
ksort($salary);
foreach($salary as $a => $a_value) {
echo "Key=" . $a . ", Value=" . $a_value;
echo "<br>";
}
?>
arsort():
Sort an associative array in descending order, according to the key.
<?php
$salary = array("Shikha"=>"45000", "Neha"=>"35000", "Ravi"=>"40000");
arsort($salary);
foreach($salary as $a => $a_value) {
echo "Key=" . $a . ", Value=" . $a_value;
echo "<br>";
}
?>
krsort():
Sort an associative array in descending order, according to the key.
<?php
$salary = array("Shikha"=>"45000", "Neha"=>"35000", "Ravi"=>"40000");
krsort($salary);
foreach($salary as $a => $a_value) {
echo "Key=" . $a . ", Value=" . $a_value;
echo "<br>";
}
?>
Simond Gear
21-Mar-2017Hi zack your explanation is very well about sorting of an array in PHP.