Backend Development 4 min read

Using PHP's array_multisort() Function to Sort Multiple Arrays

This article explains the syntax and parameters of PHP's array_multisort() function, demonstrates its usage with a concrete example sorting names, ages, and scores, and shows the resulting ordered arrays, highlighting how to sort multiple arrays simultaneously.

php中文网 Courses
php中文网 Courses
php中文网 Courses
Using PHP's array_multisort() Function to Sort Multiple Arrays

In the PHP function library, the array_multisort() function is a powerful tool that can sort multiple arrays according to specified criteria. This guide introduces its syntax, parameters, and practical usage.

1. array_multisort() Function Syntax

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

Parameters:

&$array1: Required. The array to be sorted.

$array1_sort_order: Optional. Sorting order for the first array (SORT_ASC, SORT_DESC, or default).

$array1_sort_flags: Optional. Sorting type for the first array (SORT_REGULAR, SORT_NUMERIC, SORT_STRING).

$...: Optional. Additional arrays to sort in parallel.

2. Example Demonstrating array_multisort() Usage

Assume we want to sort student names and ages based on their scores. The following code sets up three arrays and sorts them:

$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 arrays $names , $ages , and $scores , then calls array_multisort() to sort $scores in descending numeric order while reordering $names and $ages to match the new score order.

Note that the SORT_NUMERIC flag specifies numeric sorting for the scores.

3. Execution Result

Running the script yields the following ordered arrays:

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

The scores are now ranked 90, 80, 70, 60, corresponding to the names and ages: John (22), Tom (25), Mike (20), Jack (18).

Conclusion

The array_multisort() function provides a convenient way to sort multiple arrays simultaneously, improving efficiency in PHP development. Proper use of its parameters ensures correct sorting behavior and helps avoid errors.

backendPHPCode Examplesortingphp-functionsarray_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

login 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.