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
Syntax
sort(array &$array, int $flags = SORT_REGULAR): true
Parameters
| Parameter | Description |
|---|---|
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
<?php
$numbers = [5, 3, 10, 1];
sort($numbers);
echo implode(", ", $numbers), "\n";
Output
1, 3, 5, 10
<?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
<?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()returnstrue, not the sorted array:$sorted = sort($a)givestrue. Sort first, then use$a.- It throws away keys. Use
asort()to sort by value and keep keys, orksort()to sort by key.
Version history
In other languages
list.sort()· Pythonsorted()· Pythonarray.sort()· JavaScriptarray.toSorted()· JavaScript
Related
rsort()· Sort an array's values in descending order, in place. Keys are discarded and the result is renumbered from 0.asort()· Sort an array by value in ascending order, keeping each key attached to its value. Ideal for name => score maps.ksort()· Sort an array by key in ascending order, keeping each value with its key.usort()· Sort an array's values with your own comparison function, in place. Keys are discarded. Use <=> for easy comparisons.natsort()· Sort an array in natural order, so "img2" comes before "img10", keeping keys. Case-sensitive.- PHP Arrays · tutorial
- PHP Array Functions · tutorial