Using PHP rsort Function to Sort Arrays in Descending Order
This article explains the PHP rsort function, detailing its syntax, parameters, and usage for sorting arrays in descending order, provides a complete code example, and outlines additional sorting flags such as SORT_NUMERIC, SORT_STRING, SORT_LOCALE_STRING, SORT_NATURAL, and SORT_FLAG_CASE.
PHP is a popular server‑side language that provides many functions, among which the rsort function sorts arrays in descending order.
The rsort function modifies the original array and its syntax is:
rsort(array &$array, int $sort_flags = SORT_REGULAR): boolIt takes the array by reference as the first argument and an optional sorting flag as the second argument.
Example code demonstrates defining an array, applying rsort , and printing the sorted values:
<?php
$numbers = array(5, 9, 1, 3, 7);
rsort($numbers);
foreach ($numbers as $number) {
echo $number . " ";
}
?>The output will be "9 7 5 3 1", showing that the array has been reordered in descending order.
Besides the default behavior, 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 parameter to achieve different sorting strategies.
In summary, the rsort function is a convenient way to sort arrays in descending order in PHP, and by using the appropriate flags developers can tailor the sorting to their specific needs.
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.