PHP
Sorting Associative Arrays by Value while Preserving Keys in PHP
Learn to sort associative PHP arrays based on their values in ascending (`asort`) or descending (`arsort`) order, ensuring key-value pairs remain intact for consistent data representation.
<?php
$ages = [
"Peter" => "35",
"Ben" => "37",
"Joe" => "43",
"John" => "29"
];
echo "Original array:
";
print_r($ages);
// Sort by value in ascending order, preserving keys
asort($ages);
echo "
Sorted by value (ascending) with asort():
";
print_r($ages);
$products = [
"Laptop" => 1200,
"Mouse" => 25,
"Keyboard" => 75,
"Monitor" => 300
];
echo "
Original products array:
";
print_r($products);
// Sort by value in descending order, preserving keys
arsort($products);
echo "
Sorted by value (descending) with arsort():
";
print_r($products);
?>
How it works: When working with associative arrays, it's often crucial to maintain the relationship between keys and their values after sorting. Functions like `asort()` (ascending order) and `arsort()` (descending order) sort the array by its values while keeping the key-value association. This differs from `sort()` or `rsort()` which would re-index the array numerically after sorting, losing the original associative keys.