PHP Function Reference

PHP rsort() Function



The PHP rsort() function sorts an array by value in descending order. The function has one optional parameter which can be used to specify sorting behavior.

Note: This function assigns new keys to the elements in array. It removes any existing keys that may have been assigned, rather than just reordering the keys.

Syntax

rsort(array, flags)

Parameters

array Required. Specify the indexed array to sort
flags Optional. Specify sorting type flags to modify the sorting behavior. Sorting type flags:
  • SORT_REGULAR - Default. Compare items normally.
  • SORT_NUMERIC - Compare items numerically.
  • SORT_STRING - Compare items as strings.
  • SORT_LOCALE_STRING - Compare items as strings, based on current locale.
  • SORT_NATURAL - Compare items as strings using natural ordering.
  • SORT_FLAG_CASE - Compare items as strings and case-insensitive. Can be combined (bitwise OR) with SORT_STRING or SORT_NATURAL.

Return Value

Returns true on success and false in failure.

Exceptions

NA.

Example:

In the example below, rsort() function is used to sort an indexed array in descending order.

<?php
$MyArray = array("Marry", "John", "Jo", "Kim", "Adam");
rsort($MyArray);

print_r($MyArray);
?>

The output of the above code will be:

Array
(
    [0] => Marry
    [1] => Kim
    [2] => John
    [3] => Jo
    [4] => Adam
)

Example:

Consider one more example where this function is used to sort an array using case-insensitive natural ordering.

<?php
$MyArray = array("John1", "john2", "John3", "john20");
rsort($MyArray, SORT_NATURAL | SORT_FLAG_CASE);

print_r($MyArray);
?>

The output of the above code will be:

Array
(
    [0] => john20
    [1] => John3
    [2] => john2
    [3] => John1
)

❮ PHP Array Reference