PHP arsort() Function

Quick summary: The PHP arsort() function sorts an array in descending order while maintaining index association.

PHP arsort() Syntax

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

PHP arsort() Basic examples

$array = ['a'=>3,'b'=>1,'c'=>2];
arsort($array);
print_r($array);
PHP
Output:
Array ( [a] => 3 [c] => 2 [b] => 1 )

Sorts values descending while preserving keys.

PHP arsort() Real-world usage

$scores=['John'=>90,'Jane'=>85,'Adam'=>95];
arsort($scores);
print_r($scores);
PHP
Output:
Array sorted by highest score first

Rank results by highest value.

PHP arsort() Edge cases

$array=[3,1,2];
arsort($array);
print_r($array);
PHP
Output:
Array with preserved numeric keys

Numeric keys are preserved, not reindexed.

PHP arsort() Common mistakes

Confusing with rsort()

arsort() preserves keys; rsort() reindexes.

Incorrect
rsort($array);
Correct
arsort($array);

Use arsort() when key association must be preserved.

PHP arsort() Frequently Asked Questions

What does arsort() do?

Sorts an array in descending order while maintaining key association.

Use case?

Sort associative arrays.

Preserves keys?

Yes.

Return type?

bool.

Common mistake?

Expecting ascending sort.

Modifies array?

Yes.

Performance?

Fast.

Safe?

Yes.

Alternative?

asort().

Supports flags?

Yes.

Stable sort?

No.

Best practice?

Use for ranking data.

PHP arsort() Related PHP Functions