How to sort an array by keys
Short answer
ksort() sorts an array by keys, keeping the values with them:
<?php
$prices = ['tea' => 250, 'coffee' => 400, 'juice' => 180];
ksort($prices);
echo json_encode($prices);Output:
{"coffee":400,"juice":180,"tea":250}In reverse order
krsort() does that:
<?php
$sales = [2024 => 120, 2026 => 310, 2025 => 200];
krsort($sales);
echo json_encode($sales);Output:
{"2026":310,"2025":200,"2024":120}A custom order
uksort() takes a function comparing keys:
<?php
$order = ['low' => 1, 'medium' => 2, 'high' => 3];
$tasks = ['high' => 2, 'low' => 5, 'medium' => 1];
uksort($tasks, fn ($a, $b) => $order[$a] <=> $order[$b]);
echo implode(', ', array_keys($tasks));Output:
low, medium, high