๐ŸŽ“ A1Learner
๐Ÿ”
0 of 38 lessons completed

Sorting with Callbacks

Sorting with a callback orders an array by a rule the program supplies. The callback compares two values at a time and reports which one comes first.

Usort orders words by length

The comparator compares the lengths of two words with the <=> operator. Short words come first in the printed array.

<?php
$words = ["banana", "fig", "cherry", "kiwi"];
usort($words, function ($a, $b) {
  return strlen($a) <=> strlen($b);
});
print_r($words);

Uasort keeps the string keys

Each row holds a name and a score in a small array. The comparator reads the score field of two rows, and uasort keeps each key beside its row.

<?php
$rows = [
  "ana" => ["name" => "Ana", "score" => 72],
  "ben" => ["name" => "Ben", "score" => 95],
  "cid" => ["name" => "Cid", "score" => 60]
];
uasort($rows, function ($a, $b) {
  return $a["score"] <=> $b["score"];
});
print_r($rows);

Uksort orders keys by length

The comparator measures the keys instead of the values. Short keys come first, and each value stays with its key.

<?php
$stock = [
  "pen" => 5,
  "notebook" => 2,
  "ink" => 9
];
uksort($stock, function ($a, $b) {
  return strlen($a) <=> strlen($b);
});
print_r($stock);

Example

<?php
$board = [
  "Mina" => 84,
  "Omar" => 97,
  "Lena" => 76,
  "Tariq" => 89
];
uasort($board, function ($a, $b) {
  return $b <=> $a;
});
print_r($board);

Key points

  • A comparator is a callback that compares two values during a sort.
  • The <=> operator compares two values and returns -1, 0 or 1.
  • usort sorts the values of an array and renumbers its keys.
  • uasort sorts the values of an array and keeps its keys.
  • uksort sorts an array by its keys and keeps each value with its key.

In this example, the board maps each name to a score. The comparator swaps the two sides of the <=> operator, so the sort runs from the highest score down. uasort keeps each name beside its score.

Note

The sort functions change the array they are given instead of building a new one.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

Which function sorts values and keeps the original keys?