Sort Assoc Arrays by Key
Part of the Logic & Flow section of Coddy's PHP journey — lesson 23 of 68.
While sorting by values is useful, sometimes you need to organize associative arrays by their keys instead. PHP provides ksort() for ascending key order and krsort() for descending key order, both maintaining the crucial key-value relationships.
Here's how ksort() arranges an array alphabetically by its keys:
<?php
$settings = [
"theme" => "dark",
"language" => "english",
"notifications" => "enabled",
"auto_save" => "on"
];
ksort($settings);
print_r($settings);
// Outputs: Array ( [auto_save] => on [language] => english [notifications] => enabled [theme] => dark )
?>Notice how the keys are now in alphabetical order from A to Z, while each setting name remains properly paired with its value. This is particularly useful when you want to display configuration options or menu items in a predictable, organized manner.
For reverse alphabetical order, krsort() works similarly but sorts keys from Z to A. Both functions modify the original array directly, just like other PHP sorting functions, making them efficient for organizing data where the key order matters more than the value order.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
Challenge
EasyYou will receive one input: an associative array of department names and their budget allocations in JSON format. Read the input, convert the JSON string to an array, use ksort() to sort the departments alphabetically by their keys in ascending order, and print the sorted array using print_r().
Input format: One line containing a JSON object with department names as keys and budget amounts as values (example: {"Marketing":75000,"IT":120000,"HR":65000,"Finance":95000})
Expected output: The sorted associative array in ascending alphabetical order by department names (keys), displayed using print_r()
Cheat sheet
PHP provides ksort() and krsort() functions to sort associative arrays by their keys while maintaining key-value relationships.
ksort() sorts keys in ascending alphabetical order (A to Z):
ksort($array);krsort() sorts keys in descending alphabetical order (Z to A):
krsort($array);Both functions modify the original array directly:
<?php
$settings = [
"theme" => "dark",
"language" => "english",
"notifications" => "enabled",
"auto_save" => "on"
];
ksort($settings);
print_r($settings);
// Outputs: Array ( [auto_save] => on [language] => english [notifications] => enabled [theme] => dark )
?>Try it yourself
<?php
// Read input
$input = fgets(STDIN);
// Convert JSON to array
$departments = (array)json_decode($input, true);
// TODO: Write your code below to sort the array by keys
// Output the result
print_r($departments);
?>This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Advanced Functions
Anonymous FunctionsClosures and 'use'Arrow FunctionsCallback FunctionsUsing 'call_user_func'Variable FunctionsPassing by ReferenceRecursive FunctionsRecap: Function Medley4Multi-dimensional Arrays
Creating a 2D ArrayAccessing 2D Array ElementsModifying 2D Array ElementsIterating with Nested Loops2D Associative ArraysRecap: Simple Grid Exercise2Advanced Array Manipulations
Adding with 'array_push'Removing with 'array_pop'Adding with 'array_unshift'Removing with 'array_shift'Merging Indexed ArraysMerging Associative ArraysExtracting with 'array_slice'Values with 'in_array'Keys with 'array_search'Recap: Playlist Exercise3Sorting Arrays
Sort Indexed Arrays AscendingSort Indexed Arrays DescendingSort Assoc Arrays by ValueSort Assoc Arrays by KeyNatural Order SortingCustom Sorting with 'usort'Recap: Leaderboard Sorting