Using PHP array_multisort() to Sort Multiple Arrays

This article explains the PHP array_multisort() function, its syntax and parameters, and demonstrates how to sort several related arrays—such as names, ages, and scores—by a primary key using a concrete code example and the resulting output.

php Courses
php Courses
php Courses
Using PHP array_multisort() to Sort Multiple Arrays

The array_multisort() function in PHP is a powerful utility that can sort multiple arrays simultaneously according to specified ordering rules.

Syntax:

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

Parameters: &$array1 (required) – the first array to be sorted. $array1_sort_order (optional) – sorting direction for the first array (e.g., SORT_ASC or SORT_DESC). $array1_sort_flags (optional) – type of comparison for the first array (e.g., SORT_REGULAR, SORT_NUMERIC, SORT_STRING). $... (optional) – additional arrays that should be sorted in parallel with the first array.

Example usage: Suppose we want to sort three arrays—names, ages, and scores—by the scores in descending numeric order.

$names  = array('Tom', 'Jack', 'Mike', 'John');
$ages   = array('25', '18', '20', '22');
$scores = array('80', '60', '70', '90');
array_multisort($scores, SORT_DESC, SORT_NUMERIC, $names, $ages);

The code first defines the three arrays, then calls array_multisort() to sort $scores descendingly while reordering $names and $ages to maintain the association with the sorted scores.

Result:

Array
(
    [0] => John
    [1] => Tom
    [2] => Mike
    [3] => Jack
)
Array
(
    [0] => 22
    [1] => 25
    [2] => 20
    [3] => 18
)

From the output we see that the scores are ordered 90, 80, 70, 60, and the corresponding names and ages are John (22 years), Tom (25 years), Mike (20 years), and Jack (18 years).

Conclusion: array_multisort() provides a convenient way to sort multiple related arrays in PHP, improving efficiency and code clarity when handling complex data sets; however, developers must pay attention to parameter order and sorting flags to avoid errors.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

BackendSortingPHP8array_multisort
php Courses
Written by

php Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.