Skip to content
PHP Logo

What is the recommended function to use for sorting associative arrays by keys in PHP?

When sorting associative arrays by keys in PHP, the recommended function to use is `ksort()`. This function sorts the array by its keys in ascending order, maintaining the key to data correlations intact. By using `ksort()`, you can easily organize and access the elements of the associative array based on their keys.

php
// Sample associative array
$fruits = array("Banana" => 2, "Apple" => 5, "Orange" => 3);

// Sorting the associative array by keys
ksort($fruits);

// Output the sorted array
print_r($fruits);