Sorting arrays is a fundamental task in programming. PHP provides several functions to sort array elements in different ways, whether they are indexed or associative.
For indexed arrays (arrays with numeric keys), you use sort() for ascending order and rsort() for descending order.
sort()<?php
$fruits = ["Cherry", "Apple", "Banana"];
sort($fruits);
// Result: ["Apple", "Banana", "Cherry"]
?>
rsort()<?php
$numbers = [4, 2, 8, 6];
rsort($numbers);
// Result: [8, 6, 4, 2]
?>
When sorting associative arrays, you must decide if you want to sort by Value or by Key, and whether to maintain the key-value relationship.
asort()Maintains the index association (Peter is still 35).
<?php
$age = ["Peter"=>"35", "Ben"=>"37", "Joe"=>"43"];
asort($age);
?>
ksort()<?php
$age = ["Peter"=>"35", "Ben"=>"37", "Joe"=>"43"];
ksort($age);
?>
| Function | Description |
|---|---|
sort() | Sort arrays in ascending order. |
rsort() | Sort arrays in descending order. |
asort() | Sort associative arrays in ascending order, according to the value. |
ksort() | Sort associative arrays in ascending order, according to the key. |
arsort() | Sort associative arrays in descending order, according to the value. |
krsort() | Sort associative arrays in descending order, according to the key. |
asort() when you have a list of people and their ages and you want to display them from youngest to oldest without losing track of who is how old.
sort, asort, ksort.rsort, arsort, krsort.sort, asort.ksort, krsort.asort stands for **associative** (maintains associations).