Encodera

Thanks for reading!

Donate to the site — we work hard for you.

PHP reference

krsort

Sorts an array by keys in descending order.

Syntax

krsort(array &$array, int $flags = SORT_REGULAR): true

Parameters

ParameterTypeDescription
$arrayarrayThe array; changed in place.
$flagsintOptional. 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

  • ksort — Sorts an array by key.
  • arsort — Sorts an array by values in descending order, keeping the keys.
  • uksort — Sorts an array by keys using your own comparison function.

Related recipes

In the tutorial

  • Sorting arrays — Sorting in PHP — sort, rsort, asort, ksort, a custom rule with usort and the spaceship operator.

Thanks for reading!

Donate to the site — we work hard for you.