Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Contents

Sorting arrays

Lists need sorting all the time: products by price, users by name, posts by date. PHP has a whole family of functions for that. All of them change the array itself rather than return a new one.

sort and rsort

sort() sorts in ascending order, rsort() in descending order:

<?php
 
$numbers = [3, 1, 2];
 
sort($numbers);
echo implode(', ', $numbers), "\n"; // 1, 2, 3
 
rsort($numbers);
echo implode(', ', $numbers); // 3, 2, 1

Strings are sorted alphabetically.

Keeping the keys

sort() renumbers the elements. That does not suit associative arrays: the keys would be lost. asort() sorts by value and keeps the keys:

<?php
 
$prices = ['tea' => 250, 'juice' => 180, 'coffee' => 400];
 
asort($prices);
 
echo implode(', ', array_keys($prices)); // juice, tea, coffee

The companion arsort() sorts in descending order.

Sorting by key

ksort() orders an array by its keys:

<?php
 
$stock = ['pear' => 5, 'apple' => 12, 'plum' => 3];
 
ksort($stock);
 
echo implode(', ', array_keys($stock)); // apple, pear, plum

A custom rule

usort() takes a function that compares two elements. It returns a negative number if the first element should come earlier, a positive one if later, and zero if they are equal:

<?php
 
$users = [
    ['name' => 'Oleg', 'age' => 31],
    ['name' => 'Anna', 'age' => 25],
];
 
usort($users, fn ($a, $b) => $a['age'] <=> $b['age']);
 
echo implode(', ', array_column($users, 'name')); // Anna, Oleg

The spaceship operator

The <=> operator compares two values and returns -1, 0 or 1 — exactly what a comparison function needs:

<?php
 
echo 1 <=> 2, "\n"; // -1
echo 2 <=> 2, "\n"; // 0
echo 3 <=> 2;       // 1

To sort in descending order, swap the arguments: $b['age'] <=> $a['age'].

Sorting by several fields

Arrays are compared element by element, so several fields can be compared at once:

<?php
 
$users = [
    ['name' => 'Oleg', 'age' => 25],
    ['name' => 'Anna', 'age' => 31],
    ['name' => 'Anna', 'age' => 25],
];
 
usort($users, fn ($a, $b) => [$a['name'], $a['age']] <=> [$b['name'], $b['age']]);
 
echo implode(' ', array_map(fn ($user) => $user['name'] . $user['age'], $users));

This prints "Anna25 Anna31 Oleg25": by name first, and by age when the names are equal.

Common mistake

Sorting functions return true, not the sorted array. Do not assign their result:

<?php
 
$numbers = [3, 1, 2];
 
// Wrong: $numbers = sort($numbers); — the variable would hold true
 
sort($numbers);
 
echo implode(', ', $numbers); // 1, 2, 3

Thanks for reading!

Donate to the site — we work hard for you.