HTML CSS Bootstrap JavaScript jQuery MySQL PHP Data Mining

PHP Array Sorting

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.


1. Sorting Indexed Arrays

For indexed arrays (arrays with numeric keys), you use sort() for ascending order and rsort() for descending order.

Sort in Ascending Order - sort()

<?php
    $fruits = ["Cherry", "Apple", "Banana"];
    sort($fruits);
    // Result: ["Apple", "Banana", "Cherry"]
?>

Sort in Descending Order - rsort()

<?php
    $numbers = [4, 2, 8, 6];
    rsort($numbers);
    // Result: [8, 6, 4, 2]
?>

2. Sorting Associative Arrays

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.

Sort by Value (Ascending) - asort()

Maintains the index association (Peter is still 35).

<?php
    $age = ["Peter"=>"35", "Ben"=>"37", "Joe"=>"43"];
    asort($age);
?>

Sort by Key (Ascending) - ksort()

<?php
    $age = ["Peter"=>"35", "Ben"=>"37", "Joe"=>"43"];
    ksort($age);
?>

Sorting Functions Reference

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.
Note: Most of these sorting functions work in-place, meaning they modify the original array and return a boolean (true on success).
Use Case: Use 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.

Key Points

  • Ascending: sort, asort, ksort.
  • Descending: rsort, arsort, krsort.
  • Values: sort, asort.
  • Keys: ksort, krsort.
  • The 'a' in asort stands for **associative** (maintains associations).