How to sort an array
Short answer
sort() sorts the array itself in ascending order:
<?php
$numbers = [3, 1, 2];
sort($numbers);
echo implode(', ', $numbers);Output:
1, 2, 3Descending order
rsort() sorts in reverse order:
<?php
$numbers = [3, 1, 2];
rsort($numbers);
echo implode(', ', $numbers);Output:
3, 2, 1By a field
usort() sorts an array of records with a comparison function. The <=> operator returns -1, 0 or 1:
<?php
$users = [
['name' => 'Anna', 'age' => 30],
['name' => 'Oleg', 'age' => 25],
];
usort($users, fn ($a, $b) => $a['age'] <=> $b['age']);
echo implode(', ', array_column($users, 'name'));Output:
Oleg, AnnaAssociative arrays
sort() renumbers the keys. To keep them, use asort():
<?php
$prices = ['tea' => 150, 'milk' => 90];
asort($prices);
print_r($prices);Output:
Array
(
[milk] => 90
[tea] => 150
)Functions used in this recipe
- sort — Sorts an array in ascending order.
- array_reverse — Returns an array with its elements in reverse order.