PHP Reference ยท Array Functions
PHP sort() and rsort() functions
Reference for PHP sort() and rsort(): sort array values ascending or descending in place, flags for numeric and string order, key reindexing and stability.
sort() sorts the values of an array from low to high, and rsort() sorts from high to low. Both work in place: they change the variable you pass and return only true. The original keys are thrown away and replaced with 0, 1, 2, ....
Use them for plain lists. If you need to keep keys, use asort() or ksort(); if you need your own comparison, use usort().
<?php $n = [3, 1, 2]; sort($n); // [1, 2, 3] rsort($n); // [3, 2, 1]
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Syntax
sort(array &$array, int $flags = SORT_REGULAR): true rsort(array &$array, int $flags = SORT_REGULAR): true
| Name | Description |
|---|---|
$array |
The array to sort, passed by reference. |
$flags |
Comparison mode: SORT_REGULAR (default, PHP's usual comparison), SORT_NUMERIC, SORT_STRING, SORT_NATURAL and SORT_LOCALE_STRING. Add SORT_FLAG_CASE (with SORT_STRING or SORT_NATURAL) for case-insensitive order. |
Return value: always true in PHP 8.2 and later (earlier versions declared bool).
Usage notes
- In place. Writing
$sorted = sort($a);storestrue. To keep the original, copy it first:$copy = $a; sort($copy);. - Keys are lost. Use
asort()to sort values while keeping keys,ksort()to sort by key. - Stable since PHP 8.0. Elements that compare equal keep their original relative order.
- Default mode is "regular". Strings that look numeric are compared as numbers, so
"10"comes after"9". Uppercase letters sort before lowercase letters (byte order). Mixed types follow the PHP 8 comparison rules, which can be surprising; choose a flag when the data is uniform. See Sort flags and stability. - Case-insensitive:
SORT_STRING | SORT_FLAG_CASE. - Human order like
img2beforeimg10:SORT_NATURAL, ornatsort(). - Performance: about O(n log n). An explicit flag such as
SORT_NUMERICavoids the type checks of the default mode. - Descending without
rsort():sort()thenarray_reverse(), orusort()with$b <=> $a.