Sort PHP Arrays: Keys & Values

In PHP, you can use the following functions to sort the keys of an array:

  1. ksort(): Sorts the array in ascending order based on the keys.
  2. krsort(): Sorts an array in descending order by key.
  3. asort(): sort an array of key-value pairs in ascending order while maintaining the association between keys and values.
  4. arsort(): Sorts an array in descending order according to key value pairs, maintaining index association.
  5. sort(): arrange the key-value pairs in ascending order and reset the array index.
  6. 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
bannerAds