array_multisort() can sort multiple related arrays together. The later arrays follow the ordering established by earlier arrays and their sort flags.
$names = ['Ravi', 'Ana', 'Mina'];
$scores = [82, 95, 88];
array_multisort($scores, SORT_DESC, SORT_NUMERIC, $names, SORT_ASC, SORT_STRING);
print_r($scores);
print_r($names);Keep related arrays the same length so their rows stay aligned while sorting.
array_multisort(array $array1, mixed $sort_order = SORT_ASC, mixed $sort_flags = SORT_REGULAR, ...): bool
$array1 = [3, 1, 2];
$array2 = ['b', 'a', 'c'];
array_multisort($array1, SORT_ASC, $array2, SORT_ASC);
print_r($array1);
print_r($array2);
Array
(
[0] => 1
[1] => 2
[2] => 3
)
Array
(
[0] => a
[1] => c
[2] => b
)
$data = [
["name" => "John", "age" => 30],
["name" => "Jane", "age" => 25],
["name" => "Doe", "age" => 35]
];
$age = array_column($data, 'age');
array_multisort($age, SORT_ASC, $data);
print_r($data);
Array
(
[0] => Array
(
[name] => Jane
[age] => 25
)
[1] => Array
(
[name] => John
[age] => 30
)
[2] => Array
(
[name] => Doe
[age] => 35
)
)
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.