Sort PHP Arrays: Keys & Values
In PHP, you can use the following functions to sort the keys of an array:
- ksort(): Sorts the array in ascending order based on the keys.
- krsort(): Sorts an array in descending order by key.
- asort(): sort an array of key-value pairs in ascending order while maintaining the association between keys and values.
- arsort(): Sorts an array in descending order according to key value pairs, maintaining index association.
- sort(): arrange the key-value pairs in ascending order and reset the array index.
- rsort(): Sorts an array of key-value pairs in descending order and resets the array indexes.
For example, sorting a associative array by key names.
$fruits = array("apple" => "red", "banana" => "yellow", "cherry" => "red");
ksort($fruits);
foreach ($fruits as $key => $value) {
echo $key . ": " . $value . "\n";
}
The code will produce:
apple: red
banana: yellow
cherry: red