How to sort an associative array by value in PHP
In this tutorial, we are going to see how to sort an associative array by value in PHP. The PHP functions asort() and arsort() can be used to sort an array by value.
Sort an associative array by value in ascending order
You can use the asort() function to sort an associative array alphabetically by value in ascending order, while maintaining the relationship between key and value.
<?php $languages = array("p"=>"PHP", "j"=>"Java", "a"=>"Ada", "h"=>"HTML", "c"=>"CSS"); // Sorting the array by value asort($languages); print_r($languages); ?>
Output:
Array ( [a] => Ada [c] => CSS [h] => HTML [j] => Java [p] => PHP )
[st_adsense]
Sort an associative array by value in descending order
You can use the arsort() function to sort an associative array alphabetically by value in descending order, while maintaining the relationship between key and value.
[st_adsense]
<?php $languages = array("p"=>"PHP", "j"=>"Java", "a"=>"Ada", "h"=>"HTML", "c"=>"CSS"); // Sorting the array by value arsort($languages); print_r($languages); ?>
Output:
Array ( [p] => PHP [j] => Java [h] => HTML [c] => CSS [a] => Ada )[st_adsense]