arsort() function is used to sort an array in descending order based on its values. It not only sorts by the array values but also preserves the original array keys. Therefore, even if the values change, the keys stay aligned with their position in the original array.
bool arsort ( array &$array , int $sort_flags = SORT_REGULAR )
array &$array: The array to be sorted.
int $sort_flags: An optional parameter that defines the sorting rule. Common sorting rules include SORT_REGULAR (default), SORT_NUMERIC, SORT_STRING, etc.
Returns a boolean value. If sorting is successful, it returns true; otherwise, it returns false.
Here is a simple example demonstrating how to use the arsort() function to sort an array in descending order while keeping the keys intact.
<?php
$array = [
"apple" => 5,
"banana" => 2,
"orange" => 8,
"grape" => 1
];
<p>arsort($array); // Sort in descending order</p>
<p>print_r($array);<br>
?><br>
Array
(
[orange] => 8
[apple] => 5
[banana] => 2
[grape] => 1
)
As shown above, arsort() sorts the array in descending order by values and keeps the keys (such as apple, banana) unchanged.
arsort() supports specifying sorting rules via the sort_flags parameter. You can choose different sorting methods, with the most common ones being SORT_NUMERIC and SORT_STRING.
<?php
$array = [
"a" => 10,
"b" => 1,
"c" => 3
];
<p>arsort($array, SORT_NUMERIC); // Sort by numbers</p>
<p>print_r($array);<br>
?><br>
Array
(
[a] => 10
[c] => 3
[b] => 1
)
<?php
$array = [
"apple" => "green",
"banana" => "yellow",
"orange" => "orange"
];
<p>arsort($array, SORT_STRING); // Sort by strings</p>
<p>print_r($array);<br>
?><br>
Array
(
[orange] => orange
[banana] => yellow
[apple] => green
)
Suppose we have an array of student grades, and we want to sort the students in descending order by their grades while keeping their names aligned with their respective grades.
<?php
$students = [
"John" => 85,
"Jane" => 92,
"Tom" => 76,
"Lucy" => 89
];
<p>arsort($students); // Sort by grades in descending order</p>
<p>print_r($students);<br>
?><br>
Array
(
[Jane] => 92
[Lucy] => 89
[John] => 85
[Tom] => 76
)
This method is especially useful when sorting data based on criteria such as grades, scores, etc.
Not passing the array by reference
If you don't pass the array by reference, the arsort() function will not modify the original array.
<?php
$array = [
"apple" => 5,
"banana" => 2
];
<p>arsort($array); // No reference, original array won't be modified</p>
<p>print_r($array); // Outputs the original array<br>
?><br>
Array
(
[apple] => 5
[banana] => 2
)
The solution is to pass the array by reference.
arsort($array); // Modify array directly by reference
sort_flags parameter errors
In some cases, incorrect sort_flags parameters can cause unexpected sorting behavior. For example, when using SORT_STRING to sort, elements containing numbers might lead to unexpected results.