krsort()
` function to sort an associative array in descending order, according to the key of each element :<?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>";
}
?>
David is 35 years old.
Charlie is 20 years old.
Bob is 30 years old.
Alice is 25 years old.
$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. foreach
` loop and the names and ages of each person are printed to the screen.krsort()
` function works in a similar way to the `ksort()
` function, but sorts the elements in descending order instead of ascending order. arsort()
` or `asort()
` function.