PHP
Sort an Associative Array by Value Maintaining Key Association
Efficiently sort a PHP associative array by its values in ascending order, ensuring that the key-value pairs remain intact using asort for structured data.
<?php
$grades = [
"Alice" => 85,
"Bob" => 92,
"Charlie" => 78,
"David" => 92
];
asort($grades);
print_r($grades);
/* Output:
Array
(
[Charlie] => 78
[Alice] => 85
[Bob] => 92
[David] => 92
)*/
How it works: `asort()` sorts an associative array in ascending order according to the value, while maintaining the key-value association. This is crucial when you need to order data based on its values but still need to refer to the original keys, such as names or IDs, associated with those values.