[PHP] Sort a nested array by one field with usort

Created on November 30, 2026

You can use usort() to sort an array of records by one of their fields. In this example, each record contains a name and age, and the comparison orders the records by age from youngest to oldest.

<?php

$users = [
    ['name' => 'Tom', 'age' => 20],
    ['name' => 'Bob', 'age' => 10],
    ['name' => 'Alice', 'age' => 40],
    ['name' => 'James', 'age' => 30],
];

usort($users, function ($a, $b) {
    return $a['age'] <=> $b['age'];
});

var_dump($users);

The <=> operator returns a negative number, zero, or a positive number according to how the first age compares to the second. To sort from oldest to youngest, swap the operands and return $b['age'] <=> $a['age'].

The ascending sort prints:

array(4) {
  [0]=>
  array(2) {
    ["name"]=>
    string(3) "Bob"
    ["age"]=>
    int(10)
  }
  [1]=>
  array(2) {
    ["name"]=>
    string(3) "Tom"
    ["age"]=>
    int(20)
  }
  [2]=>
  array(2) {
    ["name"]=>
    string(5) "James"
    ["age"]=>
    int(30)
  }
  [3]=>
  array(2) {
    ["name"]=>
    string(5) "Alice"
    ["age"]=>
    int(40)
  }
}
PHP