PHP Sorting Arrays

In PHP, sorting arrays can be done in several ways depending on what you're trying to sort (values, keys, associative arrays, etc.). Here's a breakdown of the most common sorting functions:


1. Sorting Indexed Arrays

sort() – Sorts values in ascending order

$numbers = [4, 2, 8, 6]; sort($numbers); print_r($numbers);

rsort() – Sorts values in descending order

$numbers = [4, 2, 8, 6]; rsort($numbers); print_r($numbers);

2. Sorting Associative Arrays by Value

asort() – Sorts by values (ascending), keeps key association

$ages = ["Peter"=>35, "Ben"=>37, "Joe"=>43]; asort($ages); print_r($ages);

arsort() – Sorts by values (descending), keeps key association

arsort($ages);

3. Sorting Associative Arrays by Key

ksort() – Sorts by keys (ascending)

ksort($ages);

krsort() – Sorts by keys (descending)

krsort($ages);

4. Custom Sorting

usort() – Sorts using a custom comparison function

$people = [ ["name" => "John", "age" => 30], ["name" => "Jane", "age" => 25], ]; usort($people, function($a, $b) { return $a["age"] <=> $b["age"]; // Ascending by age }); print_r($people);