PHP
Sort Associative Array by Value (Preserve Keys)
Learn to sort associative PHP arrays by their values in ascending or descending order while preserving the key-value associations, essential for data integrity.
<?php
$scores = [
'Alice' => 85,
'Bob' => 92,
'Charlie' => 78,
'David' => 92
];
echo "Original Array:
";
print_r($scores);
// Sort by value in ascending order, preserving key association
asort($scores);
echo "
Sorted by value (ascending, asort):
";
print_r($scores);
// Sort by value in descending order, preserving key association
arsort($scores);
echo "
Sorted by value (descending, arsort):
";
print_r($scores);
?>
How it works: When working with associative arrays, it's often crucial to sort based on values without losing the connection between keys and their values. The `asort()` function sorts an array by its values in ascending order, while `arsort()` sorts in descending order. Both functions maintain the index-key association, which means the keys remain linked to their original values after the sort operation, unlike `sort()` which re-indexes numeric arrays.