PHP 8 reference · Array Sorting Functions

PHP asort() Function

Sort an array by value in ascending order, keeping each key attached to its value. Ideal for name => score maps.

PHP 8 Since 4.0

Create a free account to save this page, take notes and track your progress. Sign in

Syntax

asort(array &$array, int $flags = SORT_REGULAR): true

Parameters

ParameterDescription
array The array to sort (changed in place).
flags optional SORT_REGULAR, SORT_NUMERIC, SORT_STRING, SORT_NATURAL, optionally | SORT_FLAG_CASE. Default: SORT_REGULAR

Return value

Always true.

Examples

Sort by value, keep keysTry it yourself
<?php
$prices = ["tea" => 3.5, "cake" => 12, "milk" => 1.2];
asort($prices);
print_r($prices);

Output

Array
(
    [milk] => 1.2
    [tea] => 3.5
    [cake] => 12
)
Lists keep their keysTry it yourself
<?php
$list = ["x", "c", "a"];
asort($list);
print_r($list); // numeric keys are kept too

Output

Array
(
    [2] => a
    [1] => c
    [0] => x
)

Version history

VersionChange
PHP 4.0Added
PHP 8.0Sorting is stable: elements that compare equal keep their original order.
PHP 8.2The return type is true (it was bool).

In other languages

Was this page helpful?