Sort An Associative Array in Ascending Order by key in PHP
In this tutorial we will explains how to sort an associative array in ascending order by key in PHP. You can use the ksort() function for sorting an associative array in ascending order by key, while maintaining the relationship between key and data.
Read also: Sort An Associative Array in Descending Order by key in PHP
Sort An Associative Array in Ascending Order by key
Example #1 ksort() example
<?php $colors = array("d"=>"red", "a"=>"orange", "b"=>"yellow", "c"=>"blue"); ksort($colors); foreach ($colors as $key => $val) { echo "$key = $val<br>"; } ?>
The above example will output:
a = orange b = yellow c = blue d = red