PHP Reference ยท Array Functions
PHP array_multisort() function
Reference for PHP array_multisort(): sort several arrays together or a multidimensional array by a column, with order and flag arguments and common traps.
array_multisort() sorts one array, or several arrays at once, where the arrays move together. The first array is the main sort key. Where its values are equal, the second array decides, and so on. Other arrays are reordered in the same way, so rows stay aligned.
Its most common job is sorting a list of records by a column: extract that column with array_column(), then pass it first and the data last.
<?php $names = ["Cy", "Ann", "Bob"]; $ages = [40, 31, 25]; array_multisort($ages, $names); // $ages = [25, 31, 40], $names = ["Bob", "Ann", "Cy"]
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Syntax
array_multisort( &$array1, &...$rest ): bool
Each array may be followed by an order flag and a sort-type flag, in any order, but only one of each kind per array.
| Name | Description |
|---|---|
$array1 |
The first array. It is the primary sort key. |
...$rest |
More arrays, each optionally followed by flags. |
SORT_ASC, SORT_DESC |
Order for the array before it. Default SORT_ASC. |
SORT_REGULAR, SORT_NUMERIC, SORT_STRING, SORT_NATURAL (plus SORT_FLAG_CASE) |
How to compare the values. Default SORT_REGULAR. |
Return value: true on success, false on failure.
Errors: throws ValueError when the arrays do not all have the same number of elements.
Usage notes
- In place. The array arguments are passed by reference and modified, so pass variables. Flags (
SORT_DESCand friends) are the only values you can pass as literals. - Keys: string keys are kept; integer keys are renumbered from 0.
- Flags apply to the array right before them.
array_multisort($a, SORT_DESC, $b)sorts$adescending and$bascending. - Mixed numbers and strings behave as
SORT_REGULARcomparisons do; chooseSORT_STRINGorSORT_NUMERICwhen the data is uniform. - For simple custom sorts,
usort()with the spaceship operator is often easier to read.array_multisort()is useful for several sort keys with different directions. - The sort is stable since PHP 8.0.