PHP 8 reference · Array Sorting Functions
PHP arsort() Function
Sort an array by value in descending order, keeping each key attached to its value. Great for leaderboards.
PHP 8 Since 4.0
Syntax
arsort(array &$array, int $flags = SORT_REGULAR): true
Parameters
| Parameter | Description |
|---|---|
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
<?php
$scores = ["ann" => 72, "bob" => 95, "cal" => 88];
arsort($scores);
print_r($scores);
Output
Array
(
[bob] => 95
[cal] => 88
[ann] => 72
)<?php
$votes = array_count_values(["php", "go", "php", "sql", "php", "go"]);
arsort($votes);
echo array_key_first($votes), " wins\n";
Output
php wins
Version history
Related
asort()· Sort an array by value in ascending order, keeping each key attached to its value. Ideal for name => score maps.rsort()· Sort an array's values in descending order, in place. Keys are discarded and the result is renumbered from 0.krsort()· Sort an array by key in descending order, keeping each value with its key.array_count_values()· Count how many times each value occurs in an array, returning value => count pairs.- PHP Arrays · tutorial
- PHP Array Functions · tutorial