Encodera

Thanks for reading!

Donate to the site — we work hard for you.

PHP reference

arsort

Sorts an array by values in descending order, keeping the keys.

Syntax

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

Parameters

ParameterTypeDescription
$arrayarrayThe array; changed in place.
$flagsintOptional. The comparison mode.

Return value

trueAlways `true`.

Examples

A ranking by score:

<?php
 
$scores = ['Anna' => 72, 'Oleg' => 95, 'Ivan' => 81];
arsort($scores);
 
echo json_encode($scores);

Output:

{"Oleg":95,"Ivan":81,"Anna":72}

Notes

The function changes the original array and does not return it. A plain rsort() loses the keys.

See also

  • asort — Sorts an array by value, keeping the keys.
  • rsort — Sorts an array in descending order.
  • ksort — Sorts an array by key.

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.