In this tutorial we will learn how to sort the elements of an array on the basis of the keys or values as per
the requirement.We will discuss the following sorting functions with example:
sort()
rsort()
asort()
ksort()
arsort()
krsort()
- sort() is used for sorting elements of an array in ascending order
$fruits = array('mango','grapes','apple','pineapple');
sort($fruits);
$length= sizeof($fruits);
for($i=0;$i<$length;$i++){
echo $fruits[$i];echo '<br>';
}
output:
apple
grapes
mango
pineapple
- rsort() is used for sorting elements of an array in descending order
$fruits = array('mango','grapes','apple','pineapple');
rsort($fruits);
$length= sizeof($fruits);
for($i=0;$i<$length;$i++){
echo $fruits[$i];echo '<br>';
}
output:
pineapple
mango
grapes
apple
- asort() is implemented on associate array that returns array elements sorted in ascending order with respect to their values, for each key
$fruits = array('1'=>'mango','2'=>'grapes','3'=>'apple','4'=>'pineapple');
asort($fruits);
$length= sizeof($fruits);
foreach($fruits as $key=> $key_value){
echo "Key=".$key."; value=".$key_value;echo'<br>';
}
output:
Key=3; value=apple
Key=2; value=grapes
Key=1; value=mango
Key=4; value=pineapple
- ksort is implemented on associate array that returns array element sorted in ascending order with respect to their keys
$fruits = array('1'=>'mango','2'=>'grapes','3'=>'apple','4'=>'pineapple');
ksort($fruits);
$length= sizeof($fruits);
foreach($fruits as $key=> $key_value){
echo "Key=".$key."value=".$key_value;echo'<br>';
}
output:
Key=1value=mango
Key=2value=grapes
Key=3value=apple
Key=4value=pineapple
- arsort is implemented on associate array that returns elements in descending order with respect to the values of each keys.
$fruits = array('1'=>'mango','2'=>'grapes','3'=>'apple','4'=>'pineapple');
arsort($fruits);
foreach($fruits as $key=> $key_value){
echo "Key=".$key."; value=".$key_value;echo'<br>';
}
output:
Key=4; value=pineapple
Key=1; value=mango
Key=2; value=grapes
Key=3; value=apple
- krsort is implemented on associate array that returns elements in descending order with respect to their keys
$fruits = array('1'=>'mango','2'=>'grapes','3'=>'apple','4'=>'pineapple');
krsort($fruits);
$length= sizeof($fruits);
foreach($fruits as $key=> $key_value){
echo "Key=".$key."; value=".$key_value;echo'<br>' ;
}
output:
Key=4; value=pineapple
Key=3; value=apple
Key=2; value=grapes
Key=1; value=mango
0 Comment(s)