Skip to content
Tutorials Center
My learning

Topics

Lesson 43 of 147 ยท Arrays

Sorting Arrays

Sort PHP arrays by value or key, ascending or descending, with sort, asort, ksort and their reverse forms, custom usort comparisons with <=>, multi-key and natural sorting.

Sorting is one of the most common things you'll do with an array: products by price, names alphabetically, scores from highest to lowest, file names in the order a human expects. PHP has a whole family of sorting functions, and at first their names look like alphabet soup: sort, asort, ksort, rsort, arsort, krsort, usort, uasort, uksort, natsort.

The good news is that the names follow a simple code, and once you can read it you'll always pick the right function. This lesson explains that code, the flags that control how values are compared, custom comparisons with the spaceship operator <=>, sorting by several fields, natural ordering, and the behavior every PHP developer should know: all of these functions sort in place and keep or drop keys depending on the letter in their name.

The naming code

Each sorting function name is built from a few letters in front of sort:

Letter Meaning
(none) Sort by value and throw away the keys (re-index 0, 1, 2, โ€ฆ)
a Sort by value and keep each value's key (associative)
k Sort by key
r Reverse: descending order
u Use your own comparison function (user-defined)
nat Natural order, like a human would sort img2 before img10

So arsort means "associative, reverse": by value, descending, keys kept. uksort means "user-defined comparison on keys". The full family:

Function Sorts by Order Keys
sort / rsort value ascending / descending re-indexed
asort / arsort value ascending / descending kept
ksort / krsort key ascending / descending kept
usort value, your function your rule re-indexed
uasort value, your function your rule kept
uksort key, your function your rule kept
natsort / natcasesort value, natural order ascending kept

sort and rsort: plain lists

For a simple list where the keys don't mean anything, use sort() or rsort(). They modify the array you pass and return true, not the sorted array:

PHP sort and rsort

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Because the original is changed, sort a copy when you still need the original order. Copying an array is cheap in PHP (see Arrays), so a tiny helper that sorts and returns is a common pattern:

PHP
function sorted(array $items): array
{
    sort($items);   // sorts the function's own copy
    return $items;
}

asort and arsort: keep the keys

With an associative array, sort() would destroy the link between keys and values. asort() and arsort() sort by value but carry each key along. This is what you want for "price by product" or "votes by candidate":

PHP asort, arsort and the cost of using sort

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Notice that Ben comes before Dev although both have 51 votes. Since PHP 8.0, all sorts are stable: elements that compare as equal keep their original relative order. Ben was listed before Dev, so he stays before Dev. Before PHP 8.0 the order of ties was unpredictable, which you may still see mentioned in older articles.

ksort and krsort: sort by key

ksort() orders an array by its keys. It's useful for dictionaries you want to display alphabetically, for normalizing data before comparing or hashing it, and for arrays keyed by year or ID:

PHP Sorting by key

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

How values are compared: sort flags

The non-u functions take an optional flags argument that decides how values are compared:

Flag Compares
SORT_REGULAR (default) Normally: numbers numerically, numeric strings as numbers, other strings byte by byte
SORT_NUMERIC As numbers
SORT_STRING As strings, byte by byte
SORT_NATURAL As strings, in natural order
SORT_FLAG_CASE Combine with SORT_STRING or SORT_NATURAL to ignore case
PHP The same data, different flags

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Two lessons from this output:

  • Numeric strings such as '10' and '9' are compared as numbers by default, but as text with SORT_STRING, where '10' comes before '2' because '1' comes before '2'.
  • String comparison is byte by byte, and all uppercase ASCII letters come before all lowercase ones. That's why Cherry sorts first. Use SORT_FLAG_CASE to ignore case.

Byte order is not alphabetical order for accented letters: รฉ sorts after z. Language-aware sorting ("collation") needs the intl extension's Collator class, which isn't installed on our runner but is common in production. Without it, a practical approach for simple cases is to compare simplified versions of the strings in usort().

Avoid sorting arrays that mix numbers and non-numeric strings. PHP 8 compares a number with a non-numeric string as strings, which makes the overall order hard to predict. Clean or convert the data first.

Custom comparisons with usort and <=>

When the order depends on your own rule (sort products by price, people by age, dates by day of week), use usort(), uasort() or uksort(). You pass a comparison function that receives two elements, $a and $b, and returns:

  • a negative number if $a should come first,
  • zero if they're equal,
  • a positive number if $b should come first.

The spaceship operator <=> returns exactly that (-1, 0 or 1), so most comparison functions are one line. For descending order, swap the operands: $b <=> $a.

PHP usort with the spaceship operator

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Look at the second line of output. Kettle and Blender both have a rating of 4.4, and they stay in the order the previous sort left them (Kettle, the cheaper one, first). Stability lets you build multi-level orders by sorting several times, from the least important key to the most important.

Don't return a boolean like $a['price'] > $b['price'] from a comparison function. It can't express "equal" or "smaller", so the result can be wrong, and PHP 8 emits Deprecated: usort(): Returning bool from comparison function is deprecated. Always return an int, ideally from <=>.

Sorting by several fields

The neatest way to sort by more than one field is to compare arrays with <=>. PHP compares arrays element by element, from the first to the last, which is exactly "sort by the first field, then by the second when the first is equal":

PHP Multi-key sorting

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The trick for mixing directions is in where each value goes: for ascending fields, $a's value is on the left; for the descending score, $b's value is on the left. Read the two arrays column by column and it stays clear.

uasort and uksort

uasort() is usort() that keeps keys, and uksort() compares keys instead of values. Here's a custom order that isn't alphabetical at all, using a lookup table of positions:

PHP A custom order with uksort and uasort

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

When priorities are a fixed set like this, an enum with a method that returns the rank is even cleaner; see Class Constants and Enums.

Natural order: natsort and SORT_NATURAL

Byte order puts file10.txt before file2.txt, because it compares character by character and '1' < '2'. Natural order treats runs of digits as numbers, the way people read them. natsort() keeps keys and is case-sensitive; natcasesort() ignores case. With sort(), use the SORT_NATURAL flag, optionally with SORT_FLAG_CASE:

PHP Natural sorting of file names

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

natsort() fixes the numbers (img2 now comes before img10) but still puts IMG3.png first, because uppercase letters sort before lowercase ones. natcasesort() fixes both. The print_r output shows that the natural functions keep the original keys, like asort().

For real software version numbers, version_compare() is more accurate (it understands suffixes such as -beta and RC1), and works nicely inside usort(): usort($versions, version_compare(...)).

Sorting several arrays together: array_multisort

array_multisort() sorts one array and reorders other arrays the same way, like sorting spreadsheet columns together. It's handy when data comes as parallel lists, but it's harder to read than usort(), so prefer usort() for arrays of records.

PHP
$names = ['Cy', 'Ann', 'Bo'];
$ages = [41, 29, 35];
array_multisort($ages, $names);   // sorts $ages, and $names follows along
// $ages is now [29, 35, 41], $names is ['Ann', 'Bo', 'Cy']

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which function sorts ['b' => 2, 'a' => 1] by value and keeps the keys?

    The "a" stands for associative: sort by value, keep keys. sort and usort re-index; ksort sorts by key.
  2. 2. What does $sorted = sort($list); put in $sorted?

    Sorting functions sort the array in place and return true. $list itself is sorted.
  3. 3. Which comparison sorts people by age from oldest to youngest?

    Swapping $a and $b reverses the order. The boolean version is deprecated and can't express equality.
  4. 4. What does sort($x, SORT_STRING) produce for $x = ['10', '9', '2']?

    As strings, comparison goes character by character, and '1' comes before '2' and '9'. Without the flag, numeric strings are compared as numbers.
  5. 5. Two products have the same price. After usort by price in PHP 8, what's their order?

    Since PHP 8.0 every sort is stable, so equal elements keep their original relative order.

Summary

  • Decode the names: a keeps keys, k sorts by key, r reverses, u takes your comparison, nat sorts naturally; plain sort()/rsort() re-index.
  • All sorting functions modify the array in place and return true; sort a copy if you need the original.
  • Flags change comparisons: SORT_STRING, SORT_NUMERIC, SORT_NATURAL, and SORT_FLAG_CASE to ignore case.
  • Comparison functions return a negative number, zero or a positive number; $a <=> $b is ascending, $b <=> $a descending. Never return a bool.
  • Compare arrays with <=> to sort by several fields: [$a['x'], $b['y']] <=> [$b['x'], $a['y']].
  • Sorts are stable since PHP 8.0, so ties keep their original order.
  • natsort(), natcasesort() and SORT_NATURAL sort img2 before img10; version_compare() handles version strings.

Next: array_map, array_filter and array_reduce, where you'll transform, filter and summarize arrays with callbacks.