The sort()
function in PHP is used to sort indexed arrays in ascending order. It reindexes the array numerically (starting from 0), and modifies the original array.
๐ง Syntax
sort(array &$array, int $flags = SORT_REGULAR): bool
$array
: The array you want to sort (passed by reference).
$flags
(optional): Controls how the sorting is done. Common flags include:
SORT_REGULAR
(default) โ Compare items normally.
SORT_NUMERIC
โ Compare items numerically.
SORT_STRING
โ Compare items as strings.
๐งช Basic Example
$fruits = ["banana", "apple", "mango", "orange"];
sort($fruits);
print_r($fruits);
Output:
Array
(
[0] => apple
[1] => banana
[2] => mango
[3] => orange
)
๐ข Numeric Sorting Example
$numbers = [10, 3, 50, 23, 7];
sort($numbers);
print_r($numbers);
Output:
Array
(
[0] => 3
[1] => 7
[2] => 10
[3] => 23
[4] => 50
)
๐ค String Sorting (Case-sensitive)
$names = ["Zack", "john", "Anna", "bob"];
sort($names);
print_r($names);
Output:
Array
(
[0] => Anna
[1] => Zack
[2] => bob
[3] => john
)
Uppercase letters are sorted before lowercase.
๐ Preserve Keys?
If you want to preserve keys while sorting, use asort()
instead of sort()
.
$prices = [
"apple" => 50,
"banana" => 20,
"mango" => 40
];
asort($prices);
print_r($prices);
Output:
Array
(
[banana] => 20
[mango] => 40
[apple] => 50
)