In this tutorial we will learn How to Sort Associative array by Key with PHP, PHP ksort() function and krsort() function are used to sort any associative array by key, in ascending and descending order respectively.
Table of Contents
PHP ksort() function
PHP ksort() function sorts associative array in ascending order according to the keys of array.
PHP krsort() function
PHP krsort() function sorts associative array in descending order according to the keys of array.
Sorting associative array by keys in ascending order
<?php
$array=array("One"=>"Apple","Two"=>"Orange","Three"=>"Mango");
ksort($array);
foreach($array as $key => $value)
{
echo "Key=" . $key . ", Value=" . $value;
echo "<br>";
}
?>
Sorting associative array by keys in descending order
<?php
$array=array("One"=>"Apple","Two"=>"Orange","Three"=>"Mango");
krsort($array);
foreach($array as $key => $value)
{
echo "Key=" . $key . ", Value=" . $value;
echo "<br>";
}
?>