PHP

Sort by Multiple Keys

admin by @admin ADMIN
Jun 12, 2026
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Stable multi-column sort for arrays of associative rows. Each column can be sorted ASC or DESC independently. Wraps usort with a chained comparator.
PHP
Raw
<?php
function multiSort(array $rows, array $columns): array {
    // $columns: ['name' => 'asc', 'age' => 'desc']
    usort($rows, function ($a, $b) use ($columns) {
        foreach ($columns as $col => $dir) {
            $av = $a[$col] ?? null;
            $bv = $b[$col] ?? null;
            $cmp = $av <=> $bv;
            if ($cmp !== 0) return strtolower($dir) === 'desc' ? -$cmp : $cmp;
        }
        return 0;
    });
    return $rows;
}

$rows = [
    ['name'=>'Bob','age'=>30],
    ['name'=>'Alice','age'=>25],
    ['name'=>'Alice','age'=>35],
];
print_r(multiSort($rows, ['name'=>'asc','age'=>'desc']));
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.