PHP ยท Chapter 22 of 44

PHP Sorting Arrays

PHP provides several built-in functions to sort arrays in different ways: by value, by key, in ascending or descending order, and while preserving or discarding original keys.

Choosing the right sorting function matters โ€” for example, sort() reindexes numeric keys, while asort() preserves the key-value associations, which is important for associative arrays.

Syntax
sort($arr);
asort($arr);
ksort($arr);

Sorting indexed arrays

sort() sorts values in ascending order and reindexes keys. rsort() does the same but in descending order.

Sorting associative arrays

asort() sorts by value while keeping keys intact, ksort() sorts by key, and their descending counterparts are arsort() and krsort().

Example 1 (php)
<?php
  $nums = [3, 1, 2];
  sort($nums);
  print_r($nums);
?>
Output
Array
(
    [0] => 1
    [1] => 2
    [2] => 3
)

sort() rearranges the values in ascending order and resets the keys to 0, 1, 2.

Example 2 (php)
<?php
  $ages = ["Ben" => 30, "Amy" => 25];
  ksort($ages);
  print_r($ages);
?>
Output
Array
(
    [Amy] => 25
    [Ben] => 30
)

ksort() sorts the array alphabetically by its keys, keeping key-value pairs together.

Key points

  • sort() and rsort() sort indexed arrays and reindex keys.
  • asort() and arsort() sort associative arrays by value, preserving keys.
  • ksort() and krsort() sort associative arrays by key.
  • Choosing the wrong sort function can break key-value relationships.
๐Ÿ’ก Note: Always check the PHP manual for the exact sort function name โ€” there are many, and it's easy to pick the wrong one.

๐Ÿ“ Quick Quiz

1. Which function sorts an associative array by key?

2. What happens to keys when you use sort()?

3. Which function sorts values in descending order while keeping keys?