array_multisort(): Sorting Multiple Arrays

array_multisort(): sort related arrays

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.

The array_multisort() function in PHP sorts multiple arrays or multi-dimensional arrays based on specific sort order and flags. It is useful for sorting related arrays simultaneously.

Syntax

array_multisort(array $array1, mixed $sort_order = SORT_ASC, mixed $sort_flags = SORT_REGULAR, ...): bool

Example 1: Sorting Multiple Arrays

$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
)

Example 2: Sorting a Multi-Dimensional Array

$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
        )
)

Conclusion

The array_multisort() function is ideal for sorting multiple arrays or multi-dimensional arrays, allowing flexible control over sorting order and flags.
array_uintersect(): intersection of arrays with Custom Comparison Difference between arrays considering values
Array REFERENCE


Subscribe to our YouTube Channel here



plus2net.com











PHP video Tutorials
✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer