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.
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 = orangeThe array is sorted alphabetically by value, while the original keys remain linked to their respective values.
Laravel 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.