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

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

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.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

BackendPHPphp-functionsasortarray-sorting
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

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.