asort
Sorts an array by value, keeping the keys.
Syntax
asort(array &$array, int $flags = SORT_REGULAR): trueParameters
| Parameter | Type | Description |
|---|---|---|
| $array | array | The array being sorted. |
| $flags | int | Optional. 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:
OlegNotes
Plain sort() would replace the product names with numbers.
See also
In the tutorial
- Sorting arrays — Sorting in PHP — sort, rsort, asort, ksort, a custom rule with usort and the spaceship operator.