PHP Array Sorting
In this page:
Sorting Indexed Arrays
sort() reorders an indexed array's values in ascending order and reindexes the keys from 0, which is what you want for a simple list but will destroy any meaningful string keys in an associative array.
Example: Sorting Indexed Arrays
<?php
$numbers = [3, 1, 4, 1, 5];
sort($numbers);
print_r($numbers);
?>
Login to try C/C++/Java/PHP code in the editor
Sorting Associative Arrays by Value
asort() and ksort() preserve key-to-value associations while sorting: asort() sorts by value, ksort() sorts by key, both keeping the original pairing intact — essential when the keys carry meaning, like usernames mapped to scores.
Example: Sorting Associative Arrays by Value
<?php
$scores = ["alice" => 90, "bob" => 75];
asort($scores);
print_r($scores);
ksort($scores);
print_r($scores);
?>
Login to try C/C++/Java/PHP code in the editor
Sorting Associative Arrays by Key
rsort(), arsort(), and krsort() are the descending-order counterparts of sort(), asort(), and ksort() respectively, useful for tasks like showing the highest scores first on a leaderboard.
Example: Sorting Associative Arrays by Key
<?php
$scores = ["alice" => 90, "bob" => 75, "carol" => 85];
arsort($scores);
print_r($scores);
?>
Login to try C/C++/Java/PHP code in the editor
Custom Sorting with usort
usort() lets you supply your own comparison function, giving full control over sort order for cases the built-in functions can't handle, such as sorting an array of associative arrays by one specific field.
Example: Custom Sorting with usort
<?php
$people = [["name" => "Bob", "age" => 25], ["name" => "Alice", "age" => 30]];
usort($people, function ($a, $b) {
return $a["age"] <=> $b["age"];
});
print_r($people);
?>
Login to try C/C++/Java/PHP code in the editor
Natural Order Sorting
Sorting functions in PHP modify the array in place and return true/false rather than returning a new sorted array, which is a common gotcha if you expect $sorted = sort($array); to work — it doesn't, sort($array) is what you need.
Example: Natural Order Sorting
<?php
$numbers = [3, 1, 2];
sort($numbers); // modifies in place, returns true/false
print_r($numbers);
?>
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 13 topics to unlock
0/13 topics done
Complete these topics first: