PHP - How to Sort an Associative Array in Ascending Order According to Key?

PHP - How to Sort an Associative Array in Ascending Order According to Key?

  • PHP
  • 1 min read

Here is an example of a PHP program to sort an Associative Array in ascending order according to the key.

In PHP, the function ksort() helps us to sort an Associative array in ascending order according to the key.

Here is the Syntax of ksort() function:

ksort(arrayvariable name);

The below is an example with ksort() function on an associative array $a:

<html>
<body>
<?php
$a=array("1"=>"january","3"=>"april","2"=>"may","4"=>"june");//here "1"(key1)=>"january"(value1),"3"(key2)=>"april"(value2),"2"(key3)=>"may"(value3),"4"(key4)=>"june"(value4)
ksort($a);
print_r($a);
?>
</body>
</html>

Output: Array ( [1] => january [2] => may [3] => april [4] => june )

$a is an Associative array with 4 elements. The predefined function ksort($a) is using to sort the array $a in ascending order according to key and the predefined function print_r() is using to print the array.

See also: