usort
usort(array &$array, callable $callback): true
Sorts an array in place with a user-supplied comparison callback and rebuilds numeric indexes.
C C23
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static int by_len(const void *a, const void *b) { // qsort needs a comparator callback
return (int)strlen(*(const char **)a) - (int)strlen(*(const char **)b);
}
int main(void) {
const char *w[] = {"banana", "fig", "kiwi", "apple"};
size_t n = sizeof w / sizeof w[0];
qsort(w, n, sizeof w[0], by_len);
printf("[");
for (size_t i = 0; i < n; i++) {
printf(i ? ", \"%s\"" : "\"%s\"", w[i]);
}
printf("]\n");
return 0;
}
["fig", "kiwi", "apple", "banana"]
C++ C++26
#include <algorithm>
#include <iostream>
#include <string>
#include <vector>
int main() {
std::vector<std::string> w{"banana", "fig", "kiwi", "apple"};
std::sort(w.begin(), w.end(), [](const std::string &a, const std::string &b) {
return a.size() < b.size(); // comparator returns bool, not int
});
std::cout << "[";
for (size_t i = 0; i < w.size(); ++i) {
if (i) std::cout << ", ";
std::cout << '"' << w[i] << '"';
}
std::cout << "]\n";
return 0;
}
["fig", "kiwi", "apple", "banana"]
C# v11.0.100
using System;
using System.Collections.Generic;
var words = new List<string> { "banana", "fig", "kiwi", "apple" };
words.Sort((a, b) => a.Length.CompareTo(b.Length)); // Comparison<T> delegate sorts in place
Console.WriteLine("[" + string.Join(", ", words.ConvertAll(w => $"\"{w}\"")) + "]");
["fig", "kiwi", "apple", "banana"]
Go v1.27.4
package main
import (
"fmt"
"sort"
)
func main() {
words := []string{"banana", "fig", "kiwi", "apple"}
sort.Slice(words, func(i, j int) bool { // less predicate on indices
return len(words[i]) < len(words[j])
})
fmt.Printf("%q\n", words)
}
["fig" "kiwi" "apple" "banana"]
Java v27.0.1
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<String> words = new ArrayList<>(List.of("banana", "fig", "kiwi", "apple"));
words.sort(Comparator.comparingInt(String::length)); // stable TimSort
System.out.println(words);
}
}
[fig, kiwi, apple, banana]
JavaScript v26.13.1
const words = ["banana", "fig", "kiwi", "apple"];
words.sort((a, b) => a.length - b.length); // numeric comparator, not string compare
console.log(words);
[ 'fig', 'kiwi', 'apple', 'banana' ]
PHP v8.6.0
$words = ["banana", "fig", "kiwi", "apple"];
usort($words, fn($a, $b) => strlen($a) <=> strlen($b)); // spaceship comparator, in place
echo json_encode($words);
["fig","kiwi","apple","banana"]
Python v3.15.2
words = ["banana", "fig", "kiwi", "apple"]
print(sorted(words, key=len)) # key function returns a sort key, not a comparator
['fig', 'kiwi', 'apple', 'banana']
Rust v1.99.1
fn main() {
let mut words = vec!["banana", "fig", "kiwi", "apple"];
words.sort_by_key(|w| w.len()); // stable sort by extracted key
println!("{:?}", words);
}
["fig", "kiwi", "apple", "banana"]
TypeScript v26.13.1
const words: string[] = ["banana", "fig", "kiwi", "apple"];
words.sort((a, b) => a.length - b.length); // numeric comparator, not string compare
console.log(words);
[ 'fig', 'kiwi', 'apple', 'banana' ]
Language differences
C: comparators return an integer (negative/zero/positive); qsort is not stable.
C++: the comparator returns bool ("a sorts before b"); std::sort is not stable (std::stable_sort is).
C#: the Comparison<T> delegate returns bool; List<T>.Sort is not guaranteed stable (C#'s LINQ OrderBy is stable).
Go: sort.Slice's less predicate returns bool; not guaranteed stable (sort.SliceStable is).
Java: List.sort (TimSort) is stable.
JavaScript: comparators return an integer; sort orders the array in place.
PHP: callback shape is the first split — comparators return an integer (negative/zero/positive); key behavior is the teaching core of this category: usort drops the original keys and rebuilds 0,1,2… numeric indexes (use uasort to keep key-value association).
Python: one arm of the first split — key= only takes a key-extraction function with no pairwise comparison (emulate a comparator via functools.cmp_to_key); sorted returns a new list and leaves the original untouched (list.sort is the in-place form).
Rust: sort_by_key takes a key-extraction function; stable.
TypeScript: same as JS — sort orders in place.