Encodera

Thanks for reading!

Donate to the site — we work hard for you.

PHP reference

sort

Sorts an array in ascending order.

Available since: PHP 4

Syntax

sort(array &$array, int $flags = SORT_REGULAR): true

Parameters

ParameterTypeDescription
$arrayarrayThe array to sort. It is passed by reference and modified.
$flagsintThe 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, 3

rsort() sorts in descending order:

<?php
 
$numbers = [3, 1, 2];
rsort($numbers);
 
echo implode(', ', $numbers);

Output:

3, 2, 1

Notes

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.

Thanks for reading!

Donate to the site — we work hard for you.