Which PHP function(s) should I use to sort an associative array by its key or value?

0 votes

There are 4 different PHP functions to sort an associative array by key/value in ascending/descending order.

- asort(): Sort by value in ascending order.
- arsort(): Sort by value in descending order.
- ksort(): Sort by key in ascending order.
- krsort(): Sort by key in 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";

}

?>

The output of the above code is as follows:

Sort by key in ascending order:

apple=>24

banana=>11

cat=>53

dog=>42

egg=>9

fat=>55

goat=>37

hat=>12

Sort by key in desceding order:

hat=>12

goat=>37

fat=>55

egg=>9

dog=>42

cat=>53

banana=>11

apple=>24

Sort by value in ascending order:

egg=>9

banana=>11

hat=>12

apple=>24

goat=>37

dog=>42

cat=>53

fat=>55

Sort by value in desceding order:

fat=>55

cat=>53

dog=>42

goat=>37

apple=>24

hat=>12

banana=>11

egg=>9