ksort
ksort(array &$array, int $flags = SORT_REGULAR): true
Sorts an array in place ascending by key while keeping key-value association.
C C23
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct {
const char *key;
int value;
} Pair;
static int by_key(const void *a, const void *b) {
return strcmp(((const Pair *)a)->key, ((const Pair *)b)->key);
}
int main(void) {
Pair ps[] = {{"b", 2}, {"a", 1}, {"c", 3}};
size_t n = sizeof ps / sizeof ps[0];
qsort(ps, n, sizeof ps[0], by_key); // no assoc array in C: sort an array of structs
printf("[");
for (size_t i = 0; i < n; i++) {
printf(i ? ", %s=%d" : "%s=%d", ps[i].key, ps[i].value);
}
printf("]\n");
return 0;
}
[a=1, b=2, c=3]
C++ C++26
#include <iostream>
#include <map>
#include <string>
int main() {
std::map<std::string, int> m{{"b", 2}, {"a", 1}, {"c", 3}}; // map keeps keys sorted
std::cout << "[";
bool first = true;
for (const auto &[k, v] : m) {
if (!first) std::cout << ", ";
first = false;
std::cout << k << "=" << v;
}
std::cout << "]\n";
return 0;
}
[a=1, b=2, c=3]
C# v11.0.100
using System;
using System.Collections.Generic;
var m = new SortedDictionary<string, int> { ["b"] = 2, ["a"] = 1, ["c"] = 3 }; // keeps keys sorted
var parts = new List<string>();
foreach (var kv in m) parts.Add($"{kv.Key}={kv.Value}");
Console.WriteLine("[" + string.Join(", ", parts) + "]");
[a=1, b=2, c=3]
Go v1.27.4
package main
import (
"fmt"
"sort"
)
func main() {
m := map[string]int{"b": 2, "a": 1, "c": 3}
keys := make([]string, 0, len(m))
for k := range m {
keys = append(keys, k)
}
sort.Strings(keys) // maps are unordered: sort the keys first
fmt.Print("[")
for i, k := range keys {
if i > 0 {
fmt.Print(", ")
}
fmt.Printf("%s=%d", k, m[k])
}
fmt.Println("]")
}
[a=1, b=2, c=3]
Java v27.0.1
import java.util.Map;
import java.util.TreeMap;
public class Main {
public static void main(String[] args) {
Map<String, Integer> m = new TreeMap<>(Map.of("b", 2, "a", 1, "c", 3)); // keeps keys sorted
System.out.println(m);
}
}
{a=1, b=2, c=3}
JavaScript v26.13.1
const m = { b: 2, a: 1, c: 3 };
// string keys keep insertion order: rebuild from key-sorted entries
const sorted = Object.fromEntries(Object.entries(m).sort(([k1], [k2]) => (k1 < k2 ? -1 : 1)));
console.log(sorted);
{ a: 1, b: 2, c: 3 }
PHP v8.6.0
$m = ["b" => 2, "a" => 1, "c" => 3];
ksort($m); // sorts by key, keeps key-value association
echo json_encode($m);
{"a":1,"b":2,"c":3}
Python v3.15.2
m = {"b": 2, "a": 1, "c": 3}
# dicts keep insertion order: rebuild from key-sorted items
print(dict(sorted(m.items())))
{'a': 1, 'b': 2, 'c': 3}
Rust v1.99.1
use std::collections::BTreeMap;
fn main() {
let m: BTreeMap<&str, i32> = [("b", 2), ("a", 1), ("c", 3)].into(); // keeps keys sorted
let parts: Vec<String> = m.iter().map(|(k, v)| format!("{}={}", k, v)).collect();
println!("[{}]", parts.join(", "));
}
[a=1, b=2, c=3]
TypeScript v26.13.1
const m: Record<string, number> = { b: 2, a: 1, c: 3 };
const sorted = Object.fromEntries(Object.entries(m).sort(([k1], [k2]) => (k1 < k2 ? -1 : 1)));
console.log(sorted);
{ a: 1, b: 2, c: 3 }
Language differences
C++: the "inherently sorted container" camp — std::map maintains key order on every insert (red-black tree), so storing data there gives ksort semantics for free (at O(log n) per insert).
C#: the "inherently sorted container" camp — SortedDictionary maintains key order on every insert (O(log n) per insert).
Go: maps remain unordered — the idiom is collecting keys + sort.Strings.
Java: the "inherently sorted container" camp — TreeMap maintains key order on every insert (O(log n) per insert).
JavaScript: the "sort a snapshot" camp — objects remember insertion order, so sorting means rebuilding via Object.fromEntries; the big trap: integer-like keys ("2", "10") are hoisted to the front in ascending numeric order ahead of insertion order — only non-integer-like string keys follow insertion order strictly, so ksort semantics break for those keys.
PHP: ksort sorts ascending by key and keeps key-value association (the PHP array itself records order, so sorting rearranges it); use krsort for descending.
Python: implementation camps — the "sort a snapshot" camp: native dicts remember insertion order, so sorting means rebuilding (dict(sorted(d.items()))).
Rust: the "inherently sorted container" camp — BTreeMap maintains key order on every insert (O(log n) per insert).