Backend Development 2 min read

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.

Laravel Tech Community
Laravel Tech Community
Laravel Tech Community
Using arsort() to Sort Arrays in Reverse Order While Preserving Index Association in PHP

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 = apple
backendphpCode Examplearray-sortingarsort
Laravel Tech Community
Written by

Laravel Tech Community

Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.