← Back to PHP Course | Chapter 7: Arrays | Lesson 11 of 13

PHP Array Sorting

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
<?php
$numbers = [3, 1, 4, 1, 5];
sort($numbers);
print_r($numbers);
?>

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
<?php
$scores = ["alice" => 90, "bob" => 75];
asort($scores);
print_r($scores);
ksort($scores);
print_r($scores);
?>

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
<?php
$scores = ["alice" => 90, "bob" => 75, "carol" => 85];
arsort($scores);
print_r($scores);
?>

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
<?php
$people = [["name" => "Bob", "age" => 25], ["name" => "Alice", "age" => 30]];
usort($people, function ($a, $b) {
    return $a["age"] <=> $b["age"];
});
print_r($people);
?>

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
<?php
$numbers = [3, 1, 2];
sort($numbers); // modifies in place, returns true/false
print_r($numbers);
?>

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.