PHP rsort()
Anonymous contributor
Published Aug 8, 2023
The rsort() function sorts an indexed array in descending order. The sorting is done in place in lieu of returning a sorted copy.
Syntax
rsort(arrayToSort, sortType)
arrayToSort: An array - required parameter, specifies the array to sort.sortType: A sort type - optional flag parameter, specifies how to compare the array elements.
Note: If two members compare as equal, they retain their original order. Prior to PHP 8.0.0, their relative order in the sorted array was undefined.
Sorting Flags
SORT_REGULAR: Compare items normally.SORT_NUMERIC: Compare items numerically.SORT_STRING: Compare items as strings.SORT_LOCALE_STRING: Compare items as strings, based on the current locale option (setlocale()).SORT_NATURAL: Compare items as strings using “natural ordering” likenatsort().SORT_FLAG_CASE: Sort strings case-insensitively with other flag options (SORT_STRING,SORT_NATURAL).
Example
In this example fruits is sorted in descending order.
<?php$fruits = array("Grapes", "Mangos", "Cherries", "Kiwis");rsort($fruits);foreach ($fruits as $key => $val) {echo "$key = $val\n";}?>
The output looks like this:
0 = Mangos1 = Kiwis2 = Grapes3 = Cherries
Codebyte Example
The following example sorts numbers with the SORT_STRING flag.
All contributors
- Anonymous contributor
Learn PHP on Codecademy
- Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
- Includes 6 Courses
- With Professional Certification
- Beginner Friendly.75 hours