Sort An Associative Array in Descending Order by Value in PHP
In this tutorial we will explains how to sort an associative array in descending order by value in PHP. You can use the arsort() function for sorting an associative array in descending order by value, while maintaining the relationship between key and data.
Read also: Sort An Associative Array In Ascending Order By Value In PHP
Sort An Associative Array in Descending Order by Value
Example #1 arsort() example
<?php $colors = array("d"=>"red", "a"=>"orange", "b"=>"yellow", "c"=>"blue"); arsort($colors); foreach ($colors as $key => $val) { echo "$key = $val<br>"; } ?>
The above example will output:
b = yellow d = red a = orange c = blue
Example #2 arsort() example
<?php $age = array("Tom"=>"36", "Charlie"=>"56", "Harry"=>"26", "Alen"=>"16", "Bob"=>"72"); arsort($age); foreach ($age as $key => $val) { echo "$key = $val<br>"; } ?>
The above example will output:
Bob = 72 Charlie = 56 Tom = 36 Harry = 26 Alen = 16