Sort Arrays in PHP

Last updated: August 26, 2026.

Choose a PHP sorting function based on whether you are sorting values or keys and whether key associations must be preserved. The functions sort the array in place.

FunctionSortsPreserves key association
sort() / rsort()Values ascending/descendingNo; numeric keys are reassigned
asort() / arsort()Values ascending/descendingYes
ksort() / krsort()Keys ascending/descendingYes
usort() / uasort()Values with a callbackuasort only

Common examples

<?php
$names = ['file20', 'File3', 'file1'];
sort($names, SORT_NATURAL | SORT_FLAG_CASE);

$prices = ['basic' => 20, 'pro' => 50, 'team' => 35];
asort($prices, SORT_NUMERIC);

$users = [
    ['name' => 'Mina', 'score' => 84],
    ['name' => 'Alex', 'score' => 92],
];
usort($users, static fn(array $a, array $b): int => $b['score'] <=> $a['score']);

sort() discards existing numeric keys, while asort() preserves associations. Avoid mixed data types unless the comparison rule is explicit. See PHP’s sorting-function comparison.

admin

admin

Leave a Reply

Your email address will not be published.