Master PHP’s array_multisort: Sort Multiple Arrays Efficiently
This guide explains the syntax, parameters, and practical usage of PHP’s array_multisort() function, showing how to sort several related arrays simultaneously with a concrete example that orders names and ages based on descending numeric scores.
1. Syntax of array_multisort()
The function signature is:
array_multisort ( array &$array1 [, mixed $array1_sort_order = SORT_ASC [, mixed $array1_sort_flags = SORT_REGULAR [, mixed $... [, mixed $... ]]]] ) : boolKey parameters: &$array1: required, the primary array to sort. $array1_sort_order: optional, sorting direction 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 that will be reordered in parallel with the first array.
2. Example usage
Suppose we have three arrays representing student names, ages, and scores, and we want to order them by score descending:
$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 call sorts $scores in descending numeric order while reordering $names and $ages to maintain the association with each score.
3. Result
After execution, the arrays become:
Array
(
[0] => John
[1] => Tom
[2] => Mike
[3] => Jack
)
Array
(
[0] => 22
[1] => 25
[2] => 20
[3] => 18
)The scores are now ordered 90, 80, 70, 60, and the corresponding names and ages are John (22), Tom (25), Mike (20), and Jack (18).
4. Conclusion
The array_multisort() function provides a powerful and concise way to sort multiple related arrays in PHP, improving code efficiency and readability. When using it, ensure the correct sort order and flag parameters to avoid unexpected results.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
php Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
