PHP Sorting Arrays
Sorting puts the values of an array into order. PHP has a family of sort functions, and each one works on the array itself.
Sorting numbers with sort
sort puts the numbers from low to high. print_r shows the keys rebuilt as 0, 1 and 2.
<?php
$numbers = [30, 10, 20];
sort($numbers);
print_r($numbers);Reversing the order with rsort
rsort puts the numbers from high to low. The largest value comes first.
<?php
$numbers = [30, 10, 20];
rsort($numbers);
print_r($numbers);sort drops the keys and asort keeps them
The first print_r shows the sorted ages under number keys, so the names are gone. A fresh copy sorted with asort keeps each name with its age.
<?php
$ages = ["Bo" => 25, "Ana" => 30];
sort($ages);
print_r($ages);
$ages = ["Bo" => 25, "Ana" => 30];
asort($ages);
print_r($ages);Sorting by key with ksort
ksort orders the pairs by their keys. The names come out in letter order, and each age stays with its name.
<?php
$ages = ["Cy" => 40, "Ana" => 30, "Bo" => 25];
ksort($ages);
print_r($ages);Example
<?php
$scores = ["Bo" => 70, "Ana" => 90, "Cy" => 60];
asort($scores);
print_r($scores);
ksort($scores);
print_r($scores);Key points
- Sorting an array means putting its values into a chosen order.
- Each sort function sorts the array in place.
- sort puts values from low to high.
- rsort puts values from high to low.
- sort rebuilds the keys as numbers starting at 0, so string keys are lost.
- asort sorts by value and keeps each key with its value.
- ksort sorts by key and keeps each pair together.
In this example, the scores array pairs each name with a score. asort puts the pairs from the lowest score to the highest, and the names stay with their scores. ksort then puts the same pairs in name order.
Note
Text values sort in letter order.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
An array pairs names with ages. Which function sorts it by age and keeps the names?