Sort An Associative Array in Descending Order by key in PHP

In this tutorial we will explains how to sort an associative array in descending order by key in PHP. You can use the krsort() function for sorting an associative array in descending order by key, while maintaining the relationship between key and data.

Read also: Sort An Associative Array In Ascending Order By Key In PHP

Sort An Associative Array in Descending Order by key

Example #1 krsort() example

<?php
$colors = array("d"=>"red", "a"=>"orange", "b"=>"yellow", "c"=>"blue");
krsort($colors);
foreach ($colors as $key => $val) {
    echo "$key = $val<br>";
}
?>

The above example will output:

d = red
c = blue
b = yellow
a = orange

Leave A Reply

Your email address will not be published.