Backend Development 2 min read

Using krsort() to Sort an Array by Keys in Reverse Order (PHP)

This article explains how the PHP krsort() function sorts an array by its keys in descending order, describes its parameters and return values, and provides a complete example with code and expected output to illustrate its usage.

Laravel Tech Community
Laravel Tech Community
Laravel Tech Community
Using krsort() to Sort an Array by Keys in Reverse Order (PHP)

The PHP function krsort() sorts an array by its keys in reverse order while preserving key‑value associations.

It accepts the array by reference and an optional sort_flags parameter to modify sorting behavior, returning TRUE on success or FALSE on failure.

Example:

"lemon",
    "a" => "orange",
    "b" => "banana",
    "c" => "apple"
);

krsort($fruits);
foreach ($fruits as $key => $val) {
    echo "$key = $val\n";
}
?>

The output will be:

d = lemon
c = apple
b = banana
a = orange
backendProgrammingphparraysortingkrsort
Laravel Tech Community
Written by

Laravel Tech Community

Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.