sort
(PHP 4, PHP 5, PHP 7, PHP 8)
Sort an array in ascending order
Description
Sorts array in place by values in ascending order.
Sort-unstable No-key-association Reset-index
Parameters
arrayThe input array.
Return Values
Always
Changelog
| Version | Description |
|---|
Examples
sort() example
<?php
$fruits = array("lemon", "orange", "banana", "apple");
sort($fruits);
foreach ($fruits as $key => $val) {
echo "fruits[" . $key . "] = " . $val . "\n";
}
?>The above example will output:
fruits[0] = apple
fruits[1] = banana
fruits[2] = lemon
fruits[3] = orangeThe fruits have been sorted in alphabetical order.
sort() example using case-insensitive natural ordering
<?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:
fruits[0] = Orange1
fruits[1] = orange2
fruits[2] = Orange3
fruits[3] = orange20The fruits have been sorted like natcasesort().
Notes
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.
Be careful when sorting arrays with mixed types values because sort() can produce unexpected results, if flags is SORT_REGULAR.
See Also
rsort()- Sorting