PHP array_multisort() Function
Quick summary: The PHP array_multisort() function sorts multiple arrays or multi-dimensional arrays at once.
PHP array_multisort() Syntax
array_multisort(array &$array1, mixed $array1_sort_order = SORT_ASC, mixed $array1_sort_flags = SORT_REGULAR, mixed ...$rest): bool
PHP
PHP array_multisort() Basic examples
$numbers = [3,1,2];
array_multisort($numbers);
print_r($numbers);
PHP
Output:
Array ( [0] => 1 [1] => 2 [2] => 3 )
Sorts an array in ascending order.
PHP array_multisort() Real-world usage
$names = ['John','Jane','Adam'];
$ages = [25,22,30];
array_multisort($ages, SORT_ASC, $names);
print_r($names);
PHP
Output:
Array ( [0] => Jane [1] => John [2] => Adam )
Sorts names based on corresponding ages.
PHP array_multisort() Edge cases
$a = [3,1,2];
$b = ['c','a','b'];
array_multisort($a, $b);
print_r($b);
PHP
Output:
Array reordered to match sorted first array
Secondary arrays are reordered according to the first array.
PHP array_multisort() Common mistakes
Forgetting arrays are sorted by reference
array_multisort() modifies the original arrays.
Incorrect
array_multisort($arr);
Correct
$copy = $arr; array_multisort($copy);
Create a copy if original order must be preserved.
PHP array_multisort() Frequently Asked Questions
What does array_multisort() do?
Sorts multiple arrays or multidimensional arrays.
Use case?
Sorting related arrays.
Modifies array?
Yes.
Common mistake?
Losing key associations.
Return type?
bool.
Supports flags?
Yes.
Performance?
Moderate.
Safe?
Yes.
Alternative?
usort().
Handles objects?
Yes.
Stable sort?
No.
Best practice?
Prepare data first.