Using PHP rsort Function to Sort Arrays in Descending Order

This article explains the PHP rsort function, its syntax, parameters, and sorting flags, and provides a step‑by‑step code example that demonstrates how to sort an array in descending order and output the result, along with a brief overview of additional sorting options.

php Courses
php Courses
php Courses
Using PHP rsort Function to Sort Arrays in Descending Order

PHP is a widely used server‑side scripting language that offers many built‑in functions; among them, the rsort function can sort an array in descending order.

The function sorts the original array by reference, does not return a new array, and its syntax is:

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

It accepts two parameters: the first is the array to be sorted (passed by reference), and the optional second parameter is a sorting flag that determines the algorithm used; by default it uses SORT_REGULAR.

The following example demonstrates how to use rsort to sort a numeric array in descending order and print the result:

<?php
$numbers = array(5, 9, 1, 3, 7);

// Use rsort to sort the array in descending order
rsort($numbers);

// Print the sorted array
foreach ($numbers as $number) {
    echo $number . " ";
}
?>

In the example, we define $numbers as an array of integers, call rsort($numbers), and then iterate over $numbers to echo each value.

Running the script outputs 9 7 5 3 1, confirming that the array has been reordered in descending order and the original variable has been modified.

Besides the default descending sort, rsort supports several sorting flags such as SORT_NUMERIC, SORT_STRING, SORT_LOCALE_STRING, SORT_NATURAL, and SORT_FLAG_CASE, which can be passed as the second argument to achieve different ordering behaviors.

In summary, rsort is a convenient PHP function for quickly sorting arrays in descending order, and by using the appropriate flags developers can tailor the sorting to their specific needs.

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.

backend-developmentPHParray sortingrsortsorting flags
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.