Skip to content
Tutorials Center
My learning

Topics

PHP Reference ยท Array Functions

PHP asort() and arsort() functions

Reference for PHP asort() and arsort(): sort an array by value, ascending or descending, while keeping every key attached to its value, with flags and examples.

asort() sorts an array by its values from low to high and arsort() sorts from high to low. The "a" stands for associative: every value stays attached to its original key, so the array still tells you which key had which value, only the order of the entries changes.

Both functions work in place and return true. Use them for maps such as scores by player or prices by product. For plain lists where keys do not matter, sort() is enough.

PHP
<?php
$scores = ["ana" => 70, "ben" => 95, "cy" => 82];
asort($scores);    // ana, cy, ben
arsort($scores);   // ben, cy, ana

Try it

PHP Ranking a score table

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.

PHP Ties and 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.

Syntax

PHP
asort(array &$array, int $flags = SORT_REGULAR): true
arsort(array &$array, int $flags = SORT_REGULAR): true
Name Description
$array The array to sort, passed by reference.
$flags Comparison mode: SORT_REGULAR (default), SORT_NUMERIC, SORT_STRING, SORT_NATURAL or SORT_LOCALE_STRING. Combine with SORT_FLAG_CASE for case-insensitive string or natural order.

Return value: always true in PHP 8.2 and later (earlier versions declared bool).

Usage notes

  • Keys are preserved, including numeric ones. After asort() on a list, indexes are no longer 0, 1, 2, so $list[0] may not be the smallest value. Use reset() and end() or array_key_first() to reach the first and last entries.
  • In place. $sorted = asort($a); stores true, not the sorted array.
  • Stable since PHP 8.0. Entries with equal values keep their original relative order, also in arsort().
  • Sort by key instead with ksort() and krsort().
  • Custom rules (sort by a field of each element) need uasort(), which also keeps keys.
  • Re-index afterwards with array_values() if you need a clean list.
  • Mixed types follow PHP 8 comparison rules in the default mode. Pick a flag when the data is uniform; see Sort flags and stability.