What are the different functions in sorting an array
Q:What are the different functions in sorting an array?
Answer: The functions for sorting array are following:
1- sort($array)- is used for enumerated array(numeric array) sorts the array element in ascending order.
2- rsort($array)- is used for enumerated array,sorts the array element in descending order.
3- asort($array)- is used for associative array,sorts the array value in ascending order.
4- arsort($array)- is used for associative array,sorts the array value in descending order.
5- ksort($array)- is used for associative array,sorts the array keys in ascending order.
6- krsort($array)- is used for associative array,sorts the array keys in descending order.
These functions usage can be fairly similar with just a slight modification I will explain two functions usage here:
[CODE]<?php
$naas=array(“Xena”,”Meena”,”Teena”);
sort($naa);
?>
$Nlength=count($naa);
for($x=0;$x<$Nlength;$x++)
{
echo $naa[$x];
echo ”
“;
}
[/CODE]
The output of this would be?
Here is the output result:
Meena
Teena
Xena
Example 2:
[CODE]
<?php
$numbers=array(4,8,3,19,13);
sort($numbers);
$arrlength=count($numbers);
for($x=0;$x<$arrlength;$x++)
{
echo $numbers[$x];
echo “<br>”;
}
?>
[/CODE]
Result output:
3
4
8
13
19
krsort() Function:
The krsort() function sorts an associative array in descending order, according to the key. (i.e sorting an array in ascending order)
[CODE]
<?php
$age=array(“Orange”=>”35″,”Mango”=>”37″,”Banana”=>”43”);
krsort($price);
foreach($price as $x=>$x_value)
{
echo “Key=” . $x . “, Value=” . $x_value;
echo “<br>”;
}
?>
[/CODE]
Out Put:
Key=Orange, Value=35
Key=Mango, Value=43
Key=Banana, Value=37
Use the arsort() function to sort an associative array in descending order, according to the value (i.e sorting an array in descending order)