Sort an Associative Array by Key
Sorts an associative array by key while preserving the values assigned to each key.
Purpose
Sorts an associative array by key while preserving the values assigned to each key.
Snippet details
ContextArrayLevelProductionCopy-and-paste statusMarked safe after review.Categories
- Forms and Validation
Code
<?php
/*
* Copyright (c) 2026 Jeffery L. Paris <jparis@phpog.com>.
* Free for personal and internal use. Paid project use requires visible credit
* to Jeffery L. Paris. Corporate use requires a paid license fee unless a
* separate written license states otherwise.
*/
/**
* Sort an Associative Array by Key.
*
* Purpose:
* Sorts an associative array by keys while preserving values.
*
* @param array $values Associative values.
* @return array Key-sorted array.
*/
function ogSnippetSortAssociativeArrayByKey(array $values): array {
ksort($values, SORT_NATURAL | SORT_FLAG_CASE);
return $values;
}
$gate_addresses = array(
'P3X-888' => 'Ancient world',
'Abydos' => 'desert world',
'Atlantis' => 'city ship'
);
$sorted_addresses = ogSnippetSortAssociativeArrayByKey($gate_addresses);
foreach ($sorted_addresses as $address => $description) {
echo $address.': '.$description;
break;
}