asort

asort(array &$array, int $flags = SORT_REGULAR): true

Sorts an array in place ascending by value while keeping key-value association.

C C23

C23
#include <stdio.h>
#include <stdlib.h>

typedef struct {
    const char *name;
    int age;
} Pair;

static int by_age(const void *a, const void *b) {
    return ((const Pair *)a)->age - ((const Pair *)b)->age;
}

int main(void) {
    Pair ps[] = {{"carol", 31}, {"alice", 24}, {"bob", 19}};
    size_t n = sizeof ps / sizeof ps[0];
    qsort(ps, n, sizeof ps[0], by_age); // no assoc array in C: sort an array of structs
    for (size_t i = 0; i < n; i++) {
        printf("%s=%d\n", ps[i].name, ps[i].age);
    }
    return 0;
}
Output
bob=19
alice=24
carol=31

C++ C++26

C++26
#include <algorithm>
#include <iostream>
#include <string>
#include <utility>
#include <vector>
int main() {
    std::vector<std::pair<std::string, int>> ages{{"carol", 31}, {"alice", 24}, {"bob", 19}};
    std::sort(ages.begin(), ages.end(),
              [](const auto &a, const auto &b) { return a.second < b.second; });
    for (const auto &[name, age] : ages) std::cout << name << "=" << age << "\n";
    return 0;
}
Output
bob=19
alice=24
carol=31

C# v11.0.100

v11.0.100
using System;
using System.Collections.Generic;
using System.Linq;

var ages = new Dictionary<string, int> { ["carol"] = 31, ["alice"] = 24, ["bob"] = 19 };
foreach (var kv in ages.OrderBy(kv => kv.Value)) // LINQ returns a new ordered sequence
{
    Console.WriteLine($"{kv.Key}={kv.Value}");
}
Output
bob=19
alice=24
carol=31

Go v1.27.4

v1.27.4
package main

import (
    "fmt"
    "sort"
)

func main() {
    ages := map[string]int{"carol": 31, "alice": 24, "bob": 19}
    names := make([]string, 0, len(ages))
    for name := range ages {
        names = append(names, name)
    }
    sort.Slice(names, func(i, j int) bool { // maps are unordered: sort keys by value
        return ages[names[i]] < ages[names[j]]
    })
    for _, name := range names {
        fmt.Printf("%s=%d\n", name, ages[name])
    }
}
Output
bob=19
alice=24
carol=31

Java v27.0.1

v27.0.1
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

public class Main {
    public static void main(String[] args) {
        Map<String, Integer> ages = new HashMap<>();
        ages.put("carol", 31);
        ages.put("alice", 24);
        ages.put("bob", 19);
        var entries = new ArrayList<>(ages.entrySet());
        entries.sort(Map.Entry.comparingByValue());
        Map<String, Integer> sorted = new LinkedHashMap<>(); // rebuild in sorted order
        for (var e : entries) sorted.put(e.getKey(), e.getValue());
        System.out.println(sorted);
    }
}
Output
{bob=19, alice=24, carol=31}

JavaScript v26.13.1

v26.13.1
const ages = { carol: 31, alice: 24, bob: 19 };
// objects keep insertion order: rebuild from value-sorted entries
const sorted = Object.fromEntries(Object.entries(ages).sort((a, b) => a[1] - b[1]));
console.log(sorted);
Output
{ bob: 19, alice: 24, carol: 31 }

PHP v8.6.0

v8.6.0
$ages = ["carol" => 31, "alice" => 24, "bob" => 19];
asort($ages); // sorts by value, keeps key-value association
foreach ($ages as $name => $age) {
    echo $name, "=", $age, "\n";
}
Output
bob=19
alice=24
carol=31

Python v3.15.2

v3.15.2
ages = {"carol": 31, "alice": 24, "bob": 19}
# dicts keep insertion order: rebuild from value-sorted items
print(dict(sorted(ages.items(), key=lambda kv: kv[1])))
Output
{'bob': 19, 'alice': 24, 'carol': 31}

Rust v1.99.1

v1.99.1
fn main() {
    let mut ages = vec![("carol", 31), ("alice", 24), ("bob", 19)];
    ages.sort_by_key(|&(_, age)| age); // keep pairs together
    for (name, age) in &ages {
        println!("{}={}", name, age);
    }
}
Output
bob=19
alice=24
carol=31

TypeScript v26.13.1

v26.13.1
const ages: Record<string, number> = { carol: 31, alice: 24, bob: 19 };
const sorted = Object.fromEntries(Object.entries(ages).sort((a, b) => a[1] - b[1]));
console.log(sorted);
Output
{ bob: 19, alice: 24, carol: 31 }

Language differences

C: has no associative array, so an array of structs + qsort is the equivalent idiom.

C#: Dictionary is unordered and LINQ OrderBy (a lazy new sequence) is the handiest form (Sort() exists only on List<T>).

Go: maps are unordered, so the idiom is collect keys → sort by value → look up values.

Java: HashMap is unordered, so collect entries, sort, then insert into a LinkedHashMap.

JavaScript: object string keys keep insertion order, rebuilt via Object.fromEntries(sortedEntries).

PHP: asort sorts ascending by value and keeps the key→value association throughout — the essential difference from sort, which rebuilds numeric indexes, and the core behavior of the keyed-sort family; siblings: arsort (descending by value), ksort (by key), uasort (custom callback, keys kept).

Python: 3.7+ dicts remember insertion order, so rebuilding with dict(sorted(d.items(), key=...)) is equivalent.

Rust: BTreeMap keeps keys ordered automatically, but sorting by value needs a tuple Vec + sort_by_key.