Master PHP’s rsort: Sort Arrays Descending with Simple Code

This guide explains PHP’s rsort function, showing its syntax, parameters, and how to use it to sort arrays in descending order, while also covering optional sort flags for numeric, string, locale, natural, and case‑insensitive sorting.

php Courses
php Courses
php Courses
Master PHP’s rsort: Sort Arrays Descending with Simple Code

PHP is a widely used server‑side language that offers many built‑in functions; among them, rsort sorts an array in descending order, modifying the original array rather than returning a new one.

Function signature

rsort(array &$array, int $sort_flags = SORT_REGULAR): bool

The first argument is the array to be sorted (passed by reference). The optional second argument specifies the sorting behavior via a flag; by default, SORT_REGULAR is used.

Basic usage example

<?php
$numbers = array(5, 9, 1, 3, 7);
// Sort the array in descending order
rsort($numbers);
// Output the sorted array
foreach ($numbers as $number) {
    echo $number . " ";
}
?>

Running this script prints 9 7 5 3 1, demonstrating that the array has been reordered from highest to lowest and that the original variable is altered.

Optional sort flags

SORT_NUMERIC – sort by numeric value

SORT_STRING – sort by string value

SORT_LOCALE_STRING – sort according to the current locale

SORT_NATURAL – natural order sorting

SORT_FLAG_CASE – case‑insensitive sorting when combined with SORT_STRING or SORT_NATURAL By passing one of these flags as the second argument to rsort, developers can tailor the sorting behavior to specific data types or locale requirements.

Conclusion

The rsort function provides a quick way to sort arrays in descending order in PHP, and its optional flags allow flexible handling of numeric, string, locale‑aware, natural, and case‑insensitive sorting scenarios.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

php-functionsarray sortingrsortdescending-order
php Courses
Written by

php Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

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.