PHP 8 reference · Array Sorting Functions

PHP sort() Function

Sort an array's values in ascending order, in place. Keys are discarded and the result is renumbered from 0.

PHP 8 Since 4.0

Create a free account to save this page, take notes and track your progress. Sign in

Syntax

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

Parameters

ParameterDescription
array The array to sort (changed in place).
flags optional SORT_REGULAR, SORT_NUMERIC, SORT_STRING, SORT_NATURAL, optionally | SORT_FLAG_CASE. Default: SORT_REGULAR

Return value

Always true; the array itself is sorted.

Examples

Sort numbersTry it yourself
<?php
$numbers = [5, 3, 10, 1];
sort($numbers);
echo implode(", ", $numbers), "\n";

Output

1, 3, 5, 10
Sort strings, ignoring caseTry it yourself
<?php
$names = ["bob", "alice", "Carol"];
sort($names);
echo implode(", ", $names), "\n"; // uppercase first
sort($names, SORT_STRING | SORT_FLAG_CASE);
echo implode(", ", $names), "\n";

Output

Carol, alice, bob
alice, bob, Carol
Keys are lostTry it yourself
<?php
$prices = ["tea" => 3.5, "cake" => 12, "milk" => 1.2];
sort($prices);
print_r($prices); // keys are lost: use asort() to keep them

Output

Array
(
    [0] => 1.2
    [1] => 3.5
    [2] => 12
)

Common mistakes

  • sort() returns true, not the sorted array: $sorted = sort($a) gives true. Sort first, then use $a.
  • It throws away keys. Use asort() to sort by value and keep keys, or ksort() to sort by key.

Version history

VersionChange
PHP 4.0Added
PHP 8.0Sorting is stable: elements that compare equal keep their original order.
PHP 8.2The return type is true (it was bool).

In other languages

Was this page helpful?