PHP
Sort an Associative Array by Value
Learn to sort an associative PHP array based on its values while maintaining key-value associations using `asort()` or `arsort()` for ordered data presentation.
<?php
$scores = ['Alice' => 85, 'Bob' => 92, 'Charlie' => 78, 'David' => 92];
// Sort by value in ascending order, preserving keys
asort($scores);
echo "Sorted by value (ascending):
";
print_r($scores);
// Reset array for next sort
$scores = ['Alice' => 85, 'Bob' => 92, 'Charlie' => 78, 'David' => 92];
// Sort by value in descending order, preserving keys
arsort($scores);
echo "Sorted by value (descending):
";
print_r($scores);
?>
How it works: The `asort()` function sorts an associative array in ascending order according to its values, critically maintaining the key-value associations. This means the keys associated with values are not reset but move with their respective values. `arsort()` performs the same operation but sorts in descending order. These functions are essential when you need to order data while keeping its contextual keys intact, such as sorting user scores or product prices.