Example 1 — Sort Keys from A to Z
The pairs are rearranged so the keys are in alphabetical order.
<?php
$stock = ["banana" => 3, "apple" => 1, "cherry" => 2];
ksort($stock);
foreach ($stock as $fruit => $count) {
echo $fruit, " => ", $count, PHP_EOL;
} How It Works
- $stock has fruit names as keys, in no particular order.
- ksort() sorts the pairs by key in ascending order.
- Each count stays with its fruit name.
- The loop prints apple, banana and cherry in order.

