Using arsort() to Sort Arrays in Reverse Order While Preserving Index Association in PHP
This article explains the PHP arsort() function, its signature, parameters, return values, and provides a complete example showing how to sort an associative array in descending order while keeping the original keys linked to their values.
The arsort() function in PHP sorts an array in reverse order while maintaining index association, which is essential when the order of elements matters.
Signature: bool arsort(array &$array, int $sort_flags = SORT_REGULAR)
Description: The function reorders the array based on its values in descending order, keeping the original keys linked to their corresponding values.
Parameters:
array – the input array to be sorted.
sort_flags – optional flag to modify sorting behavior (see sort() for details).
Return value: Returns TRUE on success or FALSE on failure.
Example:
<?php
$fruits = array(
"d" => "lemon",
"a" => "orange",
"b" => "banana",
"c" => "apple"
);
arsort($fruits);
foreach ($fruits as $key => $val) {
echo "$key = $val\n";
}
?>Output:
a = orange
d = lemon
b = banana
c = appleLaravel Tech Community
Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.