Example 1 — Sort Keys from Z to A
Each pair stays together while the keys are put in descending order.
<?php
$scores = ["a" => 1, "c" => 3, "b" => 2];
krsort($scores);
foreach ($scores as $key => $value) {
echo $key, " => ", $value, PHP_EOL;
} How It Works
- $scores has the keys a, c and b in mixed order.
- krsort() sorts the pairs by key, from largest to smallest.
- Each value moves together with its key.
- The foreach loop prints the pairs in the new order: c, b, a.

