Encodera

Thanks for reading!

Donate to the site — we work hard for you.

PHP reference

array_multisort

Sorts several arrays at once, or a table by several columns.

Syntax

array_multisort(array &$array, mixed ...$rest): bool

Parameters

ParameterTypeDescription
$arrayarrayThe first array — the one sorted by.
...$restmixedThe order (`SORT_ASC`, `SORT_DESC`) and other arrays.

Return value

bool`true` on success.

Examples

A table by one column:

<?php
 
$users = [
    ['name' => 'Anna', 'age' => 31],
    ['name' => 'Oleg', 'age' => 24],
    ['name' => 'Ivan', 'age' => 28],
];
 
array_multisort(array_column($users, 'age'), SORT_ASC, $users);
 
echo implode(', ', array_column($users, 'name'));

Output:

Oleg, Ivan, Anna

Notes

usort() with the <=> operator is usually clearer: usort($users, fn ($a, $b) => $a['age'] <=> $b['age']).

See also

  • usort — Sorts an array by a custom comparison rule.
  • array_column — Pulls the values of one key out of an array of arrays.
  • sort — Sorts an array in ascending order.

In the tutorial

  • Sorting arrays — Sorting in PHP — sort, rsort, asort, ksort, a custom rule with usort and the spaceship operator.

Thanks for reading!

Donate to the site — we work hard for you.