There are 4 different PHP functions to sort an associative array by key/value in ascending/descending order.
Here is an example to show these functions:
<?php
// sort by key in ascending order
print("\nSort by key in ascending order:\n");
$arr1 = array("cat"=>53, "banana"=>11, "apple"=>24, "egg"=>9, "dog"=>42, "fat"=>55, "hat"=>12, "goat"=>37 );
ksort($arr1);
foreach($arr1 as $k=>$v){
echo $k . "=>" . $v;
echo "\n";
}
// sort by key in desceding order
print("\nSort by key in desceding order:\n");
$arr1 = array("cat"=>53, "banana"=>11, "apple"=>24, "egg"=>9, "dog"=>42, "fat"=>55, "hat"=>12, "goat"=>37 );
krsort($arr1);
foreach($arr1 as $k=>$v){
echo $k . "=>" . $v;
echo "\n";
}
// sort by value in ascending order
print("\nSort by value in ascending order:\n");
$arr1 = array("cat"=>53, "banana"=>11, "apple"=>24, "egg"=>9, "dog"=>42, "fat"=>55, "hat"=>12, "goat"=>37 );
asort($arr1);
foreach($arr1 as $k=>$v){
echo $k . "=>" . $v;
echo "\n";
}
// sort by value in desceding order
print("\nSort by value in desceding order:\n");
$arr1 = array("cat"=>53, "banana"=>11, "apple"=>24, "egg"=>9, "dog"=>42, "fat"=>55, "hat"=>12, "goat"=>37 );
arsort($arr1);
foreach($arr1 as $k=>$v){
echo $k . "=>" . $v;
echo "\n";
}
?>