Backend Development 2 min read

PHP asort() Function: Sorting Arrays While Preserving Index Association

The article explains PHP's asort() function, detailing its purpose of sorting arrays while keeping index-value relationships intact, describing its parameters and return values, and providing a complete example with code and output to illustrate its usage.

Laravel Tech Community
Laravel Tech Community
Laravel Tech Community
PHP asort() Function: Sorting Arrays While Preserving Index Association

The asort() function in PHP sorts an array while maintaining the association between its indices and values, making it useful for associative arrays where the order of elements matters.

Parameters

array – The input array to be sorted.

sort_flags – Optional flag to modify sorting behavior (default SORT_REGULAR ).

Return value

Returns TRUE on success or FALSE on failure.

Example

"lemon",
    "a" => "orange",
    "b" => "banana",
    "c" => "apple"
);
asort($fruits);
foreach ($fruits as $key => $val) {
    echo "$key = $val\n";
}
?>

Output:

c = apple
b = banana
d = lemon
a = orange

The array is sorted alphabetically by value, while the original keys remain linked to their respective values.

Backendphpphp-functionsarray-sortingasort
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.