PHP - How to Sort an Associative Array in Descending Order According to Key?

krsort() function in PHP is used to sort an Associative array in descending order according to the key.

The Syntax of krsort() function is given below:

krsort(arrayvariable name);

Here is an example on krsort() function:

<html>
<body>
<?php
$a=array("8"=>"kolkata","3"=>"barasat","2"=>"delhi","4"=>"bongaon");//here "8"(key1)=>"kolkata"(value1),"3"(key2)=>"barasat"(value2),"2"(key3)=>"delhi"(value3),"4"(key4)=>"bongaon"(value4)
krsort($a);
print_r($a);
?>
</body>
</html>

Output: Array ( [8] => kolkata [4] => bongaon [3] => barasat [2] => delhi )

Firstly, the Associative array $a is containing 4 elements. krsort($a) is sorting the array elements in descending order according to key, and the function print_r() is using to print the array.

See also:

Leave a Comment