krsort
Sorts an array by keys in descending order.
Syntax
krsort(array &$array, int $flags = SORT_REGULAR): trueParameters
| Parameter | Type | Description |
|---|---|---|
| $array | array | The array; changed in place. |
| $flags | int | Optional. The comparison mode. |
Return value
trueAlways `true`.
Examples
Newest years first:
<?php
$sales = [2024 => 120, 2026 => 310, 2025 => 200];
krsort($sales);
echo json_encode($sales);Output:
{"2026":310,"2025":200,"2024":120}Notes
To sort keys with your own function use uksort().
See also
Related recipes
In the tutorial
- Sorting arrays — Sorting in PHP — sort, rsort, asort, ksort, a custom rule with usort and the spaceship operator.