Core\Arr::sortByKey
Core\Arr::sortByKey(
array<T> $a,
{order?: Core\Arr::Order, comparator?: callable, keys?: array<int|uint|string>},
): array<T>Returns the entries of an array ordered by their keys, with every key kept.
Each value stays with its key, and nothing is renumbered. The order is the order of the characters in the key, so the key 10 comes before the key 9.
Write { order: Core\Arr::Order::Desc } for the last key first. Write { comparator: ... } with a function of two keys for another order, for example a numeric one. It returns a negative number when the first key comes first, zero for equal keys, and a positive number otherwise. Equal keys keep the order they were added in.
Write { keys: [...] } to put some keys first, in the order you list them. The other keys follow in their current order. A listed key that the array does not have is skipped. A call with both keys and comparator throws a LogicError.
The examples below show key order, the last key first, numeric keys, and one key moved to the front of every row.
Parameters
$aarray<T>The array to sort.
Options
orderCore\Arr::OrderoptionalCore\Arr::Order::Asc(the default) orCore\Arr::Order::Desc.Descreverses the comparison. Equal keys still keep the order they were added in.comparatorcallableoptionalCalled as($a, $b)on two keys, bothstrings. It returns a negative number, zero or a positive number. It replaces the natural order.keysarray<int|uint|string>optionalThe keys to put first, in this order. The other keys follow in their current order. A listed key that$adoes not have is skipped. WithDesc, the other keys come first, then the listed keys from last to first.
Return value
Returns array<T>. The same entries under the same keys, ordered by key. Without a comparator, keys are compared byte by byte, so "10" comes before "9". An array keyed by an enum (array<E, T>) gives an array<E, T> too.
Errors
RuntimeErrorThe comparator returnedNaN.LogicErrorThe call gives bothkeysandcomparator.
Changelog
| Version | Change |
|---|---|
0.0.6 | A Core\Arr function that takes a key, such as hasKey, gave a compile error for a uint key (an unsigned whole number). It now takes a uint key, as $a[$key] already did. So Core\Arr::fillKeys($ids, true) works when $ids is a list of uint values. |
Examples
The entries in key order
<?nvs// Shows how to put the entries of an array in the order of their keys. Every// key keeps its value.
array<int> $scores = ['carol' => 3, 'alice' => 1, 'bob' => 2];
// This prints alice=1, bob=2 and carol=3, one per line.foreach (Core\Arr::sortByKey($scores) as string $name => int $score) { echo $name, '=', $score, "\n";}alice=1bob=2carol=3The newest day first
<?nvs// Shows how to read the entries from the last key to the first. A report does// this to show the newest day at the top.
array<int> $visitsByDay = [ '2026-03-01' => 120, '2026-03-03' => 96, '2026-03-02' => 145,];
// A day written as 2026-03-01 sorts by its characters in the same order as by// date, so `Core\Arr::Order::Desc` gives the newest day first.array<int> $newestFirst = Core\Arr::sortByKey($visitsByDay, { order: Core\Arr::Order::Desc });
// This prints 2026-03-03, then 2026-03-02, then 2026-03-01.foreach ($newestFirst as string $day => int $visits) { echo $day, ': ', $visits, "\n";}2026-03-03: 962026-03-02: 1452026-03-01: 120Keys that are numbers
<?nvs// Shows how to order keys as numbers. Keys are text, so `9` comes after `10`// without a comparator, and a page number needs the other order.
array<string> $pages = ['10' => 'Index', '9' => 'Summary', '100' => 'Notes'];
// The comparator is given two keys. `as int` reads each key as a whole number,// and the subtraction is negative when the first number is the smaller one.array<string> $byNumber = Core\Arr::sortByKey($pages, { comparator: fn(string $a, string $b): int => ($a as int) - ($b as int),});
// This prints 9, 10 and 100, with the title of each page.foreach ($byNumber as string $page => string $title) { echo $page, ': ', $title, "\n";}9: Summary10: Index100: NotesSome keys first
<?nvs// Shows how to move one key to the front of every row in a table. The other keys// keep their order.
array<array<string>> $users = [ ['name' => 'Ida Weber', 'email' => 'ida@example.com', 'id' => '7'], ['name' => 'Tom Berg', 'email' => 'tom@example.com', 'id' => '12'],];
// `keys: ['id']` puts the key `id` first. `name` and `email` follow in their// current order, and every value stays with its key.array<array<string>> $idFirst = Core\Arr::map( $users, fn(array<string> $row): array<string> => Core\Arr::sortByKey($row, { keys: ['id'] }),);
// This prints `id=7 name=Ida Weber email=ida@example.com`, then the same for Tom.foreach ($idFirst as array<string> $row) { array<string> $pairs = Core\Arr::map($row, fn(string $value, string $key): string => $key . '=' . $value); echo Core\Str::join($pairs, ' '), "\n";}id=7 name=Ida Weber email=ida@example.comid=12 name=Tom Berg email=tom@example.com