How to sort array by key with PHP

The short answer is by using ksort(), the ksort() function is a native function that is available across PHP 4, 5, and 7. The function will sort the array to the given options, ensuring that the key to value mapping is retained during sorting. ksort() accepts two parameters, the first the array that is to be sorted and the second, any sort flags that are potentially required.

The longer answer is with this tutorial. In the following tutorial, I will demonstrate how to sort the ‘food’ array that I’ve quickly made up with some sample data by its relative keys.

Standard sorting array by key

PHP

$myArrayOfFoods = ["Bacon" => 9, "Tomatoes" => 6, "Milk" => 1, "Pasta" => 2, "Eggs" => 20, "Potato" => 17, "Broccoli" => 1, "Biscuits" => 20, "Chocolate" => 2];

var_dump($myArrayOfFoods);

ksort($myArrayOfFoods);

var_dump($myArrayOfFoods);

Output from first var_dump() (Unsorted)

array(9) { ["Bacon"]=> int(9) ["Tomatoes"]=> int(6) ["Milk"]=> int(1) ["Pasta"]=> int(2) ["Eggs"]=> int(20) ["Potato"]=> int(17) ["Broccoli"]=> int(1) ["Biscuits"]=> int(20) ["Chocolate"]=> int(2) }

Output from second var_dump() (Sorted)

["Bacon"]=> int(9) ["Biscuits"]=> int(20) ["Broccoli"]=> int(1) ["Chocolate"]=> int(2) ["Eggs"]=> int(20) ["Milk"]=> int(1) ["Pasta"]=> int(2) ["Potato"]=> int(17) ["Tomatoes"]=> int(6) }

As mentioned earlier, the ksort() function accepts both an array and optional sort flags. You can see a list of the sort_flag options on the following documentation page here. In the tutorial code above, the sort flag wasn’t required as we are simply sorting the keys and comparing them by the strings.

For more information on the ksort() and sorting in general with PHP, you can see the documentation with the following links.

Posted in PHP

Leave a Reply