Encodera

Thanks for reading!

Donate to the site — we work hard for you.

PHP reference

asort

Sorts an array by value, keeping the keys.

Syntax

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

Parameters

ParameterTypeDescription
$arrayarrayThe array being sorted.
$flagsintOptional. The comparison mode.

Return value

trueAlways `true`; the array itself is modified.

Examples

Products by ascending price:

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

Output:

{"juice":180,"tea":250,"coffee":400}

Descending — arsort():

<?php
 
$scores = ['Anna' => 82, 'Oleg' => 95];
 
arsort($scores);
 
echo array_key_first($scores);

Output:

Oleg

Notes

Plain sort() would replace the product names with numbers.

See also

  • sort — Sorts an array in ascending order.
  • ksort — Sorts an array by key.
  • usort — Sorts an array by a custom comparison rule.

In the tutorial

  • Sorting arrays — Sorting in PHP — sort, rsort, asort, ksort, a custom rule with usort and the spaceship operator.

Thanks for reading!

Donate to the site — we work hard for you.