How To Order/Sort An Associative Array By Key In PHP

In PHP, an associative array is an array with string keys rather than numeric keys. If you have an associative array and you want to sort it by key, you have several options.


One option is to use the ksort() function, which sorts the array in ascending key order. Here's an example of how to use ksort():

$fruits = array("d" => "lemon", "a" => "orange", "b" => "banana", "c" => "apple");
ksort($fruits);
foreach ($fruits as $key => $val) {
    echo "$key = $val\n";
}


This will output the following:

a = orange
b = banana
c = apple
d = lemon


If you want to sort the array in descending key order, you can use the krsort() function instead. Here's an example:

$fruits = array("d" => "lemon", "a" => "orange", "b" => "banana", "c" => "apple");
krsort($fruits);
foreach ($fruits as $key => $val) {
    echo "$key = $val\n";
}


This will output the following:

d = lemon
c = apple
b = banana
a = orange


If you want to sort the array by key in a case-insensitive manner, you can use the ksort() function with the SORT_STRING flag like this:

$fruits = array("d" => "lemon", "a" => "orange", "b" => "banana", "c" => "apple");
ksort($fruits, SORT_STRING | SORT_FLAG_CASE);
foreach ($fruits as $key => $val) {
    echo "$key = $val\n";
}


This will output the following:

a = orange
b = banana
c = apple
d = lemon


Alternatively, you can use the uksort() function to sort the associative array by key using a user-defined comparison function. For example:

function cmp($a, $b)
{
    return strcmp($a, $b);
}

$fruits = array("d" => "lemon", "a" => "orange", "b" => "banana", "c" => "apple");
uksort($fruits, "cmp");
foreach ($fruits as $key => $val) {
    echo "$key = $val\n";
}


This will output the following:

a = orange
b = banana
c = apple
d = lemon