array_multisort

Sorts several arrays at once, or a multidimensional array, by one or more columns in place.

Signature
array_multisort(array &$array1, mixed $array1_sort_order = SORT_ASC, mixed $array1_sort_flags = SORT_REGULAR, mixed ...$rest): true
  • Added in PHP 4.0

Parameters

ParameterTypeDescription
$array1arrayThe first array to sort. Passed by reference and modified in place.
$array1_sort_orderoptionalmixed= SORT_ASCSort direction for the preceding array: SORT_ASC or SORT_DESC.
$array1_sort_flagsoptionalmixed= SORT_REGULARComparison flags for the preceding array, such as SORT_REGULAR, SORT_NUMERIC, SORT_STRING or SORT_NATURAL.
$restoptionalmixedFurther arrays, each optionally followed by its own sort order and sort flags.

Return value

trueAlways true. The sorting is done in place on the arrays passed by reference.

Errors

Throws a ValueError if the arrays do not all have the same number of elements, or if a sort order or sort flag argument appears where an array is expected.

Changelog

  • PHP 8.5.0The return type is now true; previously it was bool.
  • PHP 8.0.0A ValueError is thrown on invalid arguments — mismatched array sizes, or a sort order or flag in an invalid position. Previously E_WARNING was raised and false returned.

array_multisort() sorts one array and reorders every other array you pass alongside it to match. Think of the arrays as columns of the same table: sort the first column and all the other columns follow their rows.

Reading the argument list

The arguments are positional and slightly unusual. Each array may optionally be followed by a sort order (SORT_ASC / SORT_DESC) and then a sort flag (SORT_NUMERIC, SORT_STRING, SORT_NATURAL and friends). Anything that is an array starts a new column; anything that is an int modifies the column before it. Columns are used as tiebreakers in order: the second array only decides the order where the first array has equal values.

When to reach for it

The classic use is sorting an array of rows by two or more fields — pull the fields out with array_column(), then pass those columns followed by the row array itself. Because it sorts in place and never calls back into PHP, it is noticeably faster than usort() with a comparison closure on large datasets.

Every array must have the same number of elements or you get a ValueError. All arrays are passed by reference, so you cannot feed it a function's return value directly — assign it to a variable first. String keys are preserved but integer keys are renumbered, so treat the inputs as lists.

Example

Try it yourself
Loading editor…
Press Run to execute the code.

When to use it

  • Sort a result set by department ascending, then by salary descending
  • Reorder parallel arrays of filenames and file sizes together
  • Sort a large table faster than usort by avoiding a per-comparison callback
  • Apply natural-order sorting to a version column while keeping rows aligned

Frequently asked questions

How do I sort a multidimensional array by two columns in PHP?

Extract each column with array_column(), then pass the columns followed by their sort order and finally the row array itself to array_multisort(). The rows are reordered to match the sorted columns.

What is the difference between array_multisort and usort?

usort takes a comparison callback and gives you full control over the ordering logic, while array_multisort sorts by column values only but runs entirely in C, making it faster on large arrays. Use usort when the comparison is not a simple field ordering.

Does array_multisort preserve array keys?

String keys are preserved, but integer keys are reindexed from 0. Treat the arrays you pass as plain lists to avoid surprises.

More examples

Sorting one array descending

With a single array it behaves like rsort(): the output is 91, 42, 15, 7, 7. The final var_dump shows the return value, which is always true on PHP 8.5 — never test it for failure.

Example · php
<?php
$scores = [42, 7, 91, 7, 15];
array_multisort($scores, SORT_DESC, SORT_NUMERIC);
print_r($scores);
var_dump(array_multisort($scores));

Keeping parallel arrays aligned

Only $sizes drives the ordering, but $files is permuted the same way, so name and size stay on the same row. Output lists report.pdf 98000, then notes.txt 1200, then a.log 340.

Example · php
<?php
$files = ['notes.txt', 'a.log', 'report.pdf'];
$sizes = [1200, 340, 98000];

array_multisort($sizes, SORT_DESC, $files);
foreach ($files as $i => $f) {
    echo str_pad($f, 12), $sizes[$i], "\n";
}

Mismatched lengths throw

PHP 8 throws a ValueError because the two arrays differ in size, and $a is left unsorted. Before PHP 8 this only raised a warning and returned false, which was easy to ignore.

Example · php
<?php
$a = [3, 1, 2];
$b = ['x', 'y'];
try {
    array_multisort($a, $b);
} catch (ValueError $e) {
    echo get_class($e), ': ', $e->getMessage(), "\n";
}
print_r($a);

Discussion

  • Be the first to comment on this lesson.