php8.5
Home/ Manual/ array / functions/ sort

sort

PHP function Edit on GitHub ✎

(PHP 4, PHP 5, PHP 7, PHP 8)

Sort an array in ascending order

Description

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

Sorts array in place by values in ascending order.

Sort-unstable No-key-association Reset-index

Parameters

array

The input array.

Return Values

Always

Changelog

VersionDescription

Examples

sort() example

php
<?php

$fruits = array("lemon", "orange", "banana", "apple");
sort($fruits);
foreach ($fruits as $key => $val) {
    echo "fruits[" . $key . "] = " . $val . "\n";
}

?>

The above example will output:

output
fruits[0] = apple
fruits[1] = banana
fruits[2] = lemon
fruits[3] = orange

The fruits have been sorted in alphabetical order.

sort() example using case-insensitive natural ordering

php
<?php

$fruits = array(
    "Orange1", "orange2", "Orange3", "orange20"
);
sort($fruits, SORT_NATURAL | SORT_FLAG_CASE);
foreach ($fruits as $key => $val) {
    echo "fruits[" . $key . "] = " . $val . "\n";
}

?>

The above example will output:

output
fruits[0] = Orange1
fruits[1] = orange2
fruits[2] = Orange3
fruits[3] = orange20

The fruits have been sorted like natcasesort().

Notes

Note

Like most PHP sorting functions, sort() uses an implementation of Quicksort. The pivot is chosen in the middle of the partition resulting in an optimal time for already sorted arrays. This is however an implementation detail you shouldn't rely on.

Warning

Be careful when sorting arrays with mixed types values because sort() can produce unexpected results, if flags is SORT_REGULAR.

See Also

Source: reference/array/functions/sort.xml · from the official PHP manual (php/doc-en)