PHP › Arrays in PHP

How do you sort arrays in PHP, and what is the difference between functions like sort, asort, and usort?

Intermediate

Answer

The sort function reorders an array by value and reindexes the keys numerically, asort sorts an array by value while preserving the original keys, which is useful for associative arrays, and usort lets you define a completely custom comparison function to sort elements based on any logic you need, such as sorting an array of objects by a specific property.
$scores = ['Ali' => 85, 'Sara' => 92, 'Omar' => 78];
asort($scores);

$products = [['name' => 'Pen', 'price' => 5], ['name' => 'Book', 'price' => 20]];
usort($products, fn($a, $b) => $a['price'] <=> $b['price']);
Real-world example An e commerce catalog uses usort with a custom comparison function to sort a list of products by price, letting customers view items from cheapest to most expensive.

Common follow-ups: What does the spaceship operator do in a usort comparison function?;How do you sort an array in descending order?