PHP 8 reference · Array Sorting Functions

PHP array_multisort() Function

Sort several arrays at once, or a table by several columns, keeping rows lined up. Changes the arrays in place.

PHP 8 Since 4.0

Create a free account to save this page, take notes and track your progress. Sign in

Syntax

array_multisort(array &$array1, mixed $array1_sort_order = SORT_ASC, mixed $array1_sort_flags = SORT_REGULAR, mixed ...$rest): bool

Parameters

ParameterDescription
array1 The first array to sort by.
array1_sort_order optional SORT_ASC or SORT_DESC. Default: SORT_ASC
array1_sort_flags optional Sort flags such as SORT_STRING. Default: SORT_REGULAR
rest optional More arrays, each optionally followed by its order and flags.

Return value

true on success.

Examples

Sort one array by anotherTry it yourself
<?php
$names = ["Cal", "Ann", "Bob"];
$ages = [41, 36, 29];
array_multisort($ages, $names);
print_r($names);

Output

Array
(
    [0] => Bob
    [1] => Ann
    [2] => Cal
)
Sort a table by two columnsTry it yourself
<?php
$rows = [
    ["team" => "red", "score" => 10],
    ["team" => "blue", "score" => 30],
    ["team" => "green", "score" => 10],
];
array_multisort(array_column($rows, "score"), SORT_DESC, array_column($rows, "team"), SORT_ASC, $rows);
echo implode(", ", array_column($rows, "team")), "\n";

Output

blue, green, red

Version history

VersionChange
PHP 4.0Added

Was this page helpful?