Google News
logo
PHP Program to krsort() - Sort array in descending order, according to key
In the following example of PHP program that demonstrates how to use the `krsort()` function to sort an associative array in descending order, according to the key of each element :
Program :
<?php

// Create an associative array of names and ages
$ages = array("Charlie" => 20, "Alice" => 25, "David" => 35, "Bob" => 30);

// Sort the array in descending order, according to key
krsort($ages);

// Loop through the sorted array and print the values
foreach($ages as $name => $age) {
    echo $name . " is " . $age . " years old.<br>";
}

?>
Output :
David is 35 years old.
Charlie is 20 years old.
Bob is 30 years old.
Alice is 25 years old.
In this example, we have created an associative array `$ages` containing the names and ages of some people. We use the `krsort()` function to sort the array in descending order, according to the key of each element.

The sorted array is then looped through using a `foreach` loop and the names and ages of each person are printed to the screen.

The `krsort()` function works in a similar way to the `ksort()` function, but sorts the elements in descending order instead of ascending order.

It modifies the original array in place and returns a boolean value indicating whether the sort was successful or not. If you want to sort the array according to its values, you can use the `arsort()` or `asort()` function.