sort
Sorts an array in ascending order.
Available since: PHP 4
Syntax
sort(array &$array, int $flags = SORT_REGULAR): trueParameters
| Parameter | Type | Description |
|---|---|---|
| $array | array | The array to sort. It is passed by reference and modified. |
| $flags | int | The comparison mode: `SORT_REGULAR`, `SORT_NUMERIC`, `SORT_STRING` and others. |
Return value
trueAlways `true`. The result of sorting is the modified array itself.
Examples
Sorting in ascending order:
<?php
$numbers = [3, 1, 2];
sort($numbers);
echo implode(', ', $numbers);Output:
1, 2, 3rsort() sorts in descending order:
<?php
$numbers = [3, 1, 2];
rsort($numbers);
echo implode(', ', $numbers);Output:
3, 2, 1Notes
The function modifies the array itself and renumbers the keys, so it does not suit associative arrays: use asort() (by value) and ksort() (by key) there.
See also
- array_reverse — Returns an array with its elements in reverse order.
- array_unique — Removes duplicate values from an array.
Related recipes
In the tutorial
- Arrays — Lists and associative arrays in PHP — creating, changing, iterating and useful functions.