Sort An Associative Array in Ascending Order by Value in PHP

In this tutorial we will explains how to sort an associative array in ascending order by value in PHP. You can use the asort() function for sorting an associative array in ascending order by value, while maintaining the relationship between key and data.

Read also: Sort An Associative Array In Descending Order By Value In PHP

Sort An Associative Array in Ascending Order by Value

Example #1 asort() example

<?php
$colors = array("d"=>"red", "a"=>"orange", "b"=>"yellow", "c"=>"blue");
asort($colors);
foreach ($colors as $key => $val) {
    echo "$key = $val<br>";
}
?>

The above example will output:

c = blue
a = orange
d = red
b = yellow

Example #2 asort() example

<?php
$age = array("Tom"=>"36", "Charlie"=>"56", "Harry"=>"26", "Alen"=>"16", "Bob"=>"72");
asort($age);
foreach ($age as $key => $val) {
    echo "$key = $val<br>";
}
?>

The above example will output:

Alen = 16
Harry = 26
Tom = 36
Charlie = 56
Bob = 72

Leave A Reply

Your email address will not be published.