In this tutorial we will learn How to Sort Associative array by Value with PHP, PHP asort() function and arsort() function are used to sort any associative array by value, in ascending and descending order respectively.
Table of Contents
PHP asort() function
PHP asort() function sorts associative array in ascending order according to the values of array.
PHP arsort() function
PHP arsort() function sorts associative array in descending order according to the values of array.
Sorting associative array in ascending order
<?php
$array=array("First"=>"HTML","Second"=>"CSS","Third"=>"JavaScript","Fourth"=>"PHP");
asort($array);
foreach($array as $key=>$value)
{
echo "Key=" . $key . ", Value=" . $value;
echo "<br>";
}
?>
Sorting associative array in descending order
<?php
$array=array("First"=>"HTML","Second"=>"CSS","Third"=>"JavaScript","Fourth"=>"PHP");
arsort($array);
foreach($array as $key=>$value)
{
echo "Key=" . $key . ", Value=" . $value;
echo "<br>";
}
?>