PHP array_multisort() Function

PHP

PHP array_multisort() - Sort Multiple Arrays

SEO Description: Learn PHP array_multisort() function. Sort multiple arrays simultaneously or sort multidimensional arrays with advanced sorting options.

Introduction

When working with arrays in PHP, sorting is a common operation. But what if you need to sort multiple arrays in tandem or sort a multidimensional array based on one or more sub-keys? The array_multisort() function is your powerful built-in tool for such scenarios.

This tutorial will guide you through understanding and using array_multisort() effectively, with practical examples and best practices for sorting complex data structures.

Prerequisites

  • Basic knowledge of PHP syntax and arrays.
  • Familiarity with PHP sorting functions (e.g., sort(), asort()).
  • PHP environment (version 5.x or higher recommended).

Setup Steps

  1. Ensure PHP is installed on your system (check with php -v).
  2. Create a PHP file, e.g., array_multisort_example.php.
  3. Prepare arrays you want to sort or multidimensional arrays with sortable subarrays.
  4. Use array_multisort() to sort these arrays with desired sorting order and flags.

Understanding array_multisort()

The array_multisort() function sorts multiple arrays or multi-dimensional arrays. Its signature looks like this:

bool array_multisort(array &$array1 [, int $sort_order = SORT_ASC [, int $sort_flags = SORT_REGULAR [, array &... ]]] )

Parameters:

  • $array1, ...: The one or more arrays passed by reference to be sorted.
  • $sort_order: Sorting order (SORT_ASC or SORT_DESC).
  • $sort_flags: Sort behavior flags (e.g. SORT_REGULAR, SORT_NUMERIC, SORT_STRING). Defaults to SORT_REGULAR.

The function sorts the first array according to the specified order and flags and applies the sorting results on all following arrays in parallel.

Examples

Example 1: Sorting Multiple Arrays in Sync

Sort two arrays simultaneously, where the first array is sorted in ascending order and the second array rearranges accordingly.

<?php
$names = ["John", "Jane", "Doe", "Alice"];
$ages  = [25, 22, 23, 28];

// Sort $ages ascending and sort $names to maintain correlation with $ages
array_multisort($ages, SORT_ASC, $names);

print_r($ages);
print_r($names);
?>

Output:

Array
(
    [0] => 22
    [1] => 23
    [2] => 25
    [3] => 28
)
Array
(
    [0] => Jane
    [1] => Doe
    [2] => John
    [3] => Alice
)

Example 2: Sorting a Multidimensional Array Using Columns

Sort a multidimensional array by one or multiple columns.

<?php
$data = [
    ["id" => 3, "name" => "Alice", "score" => 85],
    ["id" => 1, "name" => "John",  "score" => 90],
    ["id" => 2, "name" => "Jane",  "score" => 90],
];

// Extract the columns we want to sort by
$score = array_column($data, 'score');
$name  = array_column($data, 'name');

// Sort by score descending, then by name ascending
array_multisort(
    $score, SORT_DESC, SORT_NUMERIC,
    $name, SORT_ASC, SORT_STRING,
    $data
);

print_r($data);
?>

Output:

Array
(
    [0] => Array
        (
            [id] => 1
            [name] => John
            [score] => 90
        )
    [1] => Array
        (
            [id] => 2
            [name] => Jane
            [score] => 90
        )
    [2] => Array
        (
            [id] => 3
            [name] => Alice
            [score] => 85
        )
)

Example 3: Sorting Arrays with Different Sort Flags

Sort one array as numeric and the other as a string, applying different sort flags.

<?php
$numbers = ['10', '2', '30', '25'];
$letters = ['d', 'a', 'c', 'b'];

// Sorting $numbers as integers ascending; letters alphabetically descending
array_multisort(
    $numbers, SORT_ASC, SORT_NUMERIC,
    $letters, SORT_DESC, SORT_STRING
);

print_r($numbers);
print_r($letters);
?>

Output:

Array
(
    [0] => 2
    [1] => 10
    [2] => 25
    [3] => 30
)
Array
(
    [0] => a
    [1] => d
    [2] => b
    [3] => c
)

Best Practices

  • Always pass arrays by reference; array_multisort() modifies the input arrays.
  • For multidimensional arrays, extract columns with array_column() to sort by specific keys.
  • Use explicit sort order and flags for predictable results (SORT_ASC, SORT_DESC, SORT_NUMERIC, SORT_STRING).
  • Be cautious mixing data types; inconsistent types can yield unexpected sorting results.
  • Check the return value (boolean) to confirm if sorting succeeded.

Common Mistakes

  • Not passing arrays by reference – pass variables directly, not copies.
  • Ignoring sort flags and orders – defaults can produce unexpected behavior.
  • Attempting to sort associative arrays without keys alignment – array_multisort() works best with indexed arrays or aligned keys.
  • Forgetting to extract data columns before sorting a multidimensional array.
  • Using array_multisort() when usort() with a custom comparator might be more appropriate for complex sorting criteria.

Interview Questions

Junior-Level Questions

  • Q1: What does the array_multisort() function do in PHP?
    A: It sorts multiple arrays simultaneously or sorts a multidimensional array by one or more columns.
  • Q2: How do you pass arrays to the array_multisort() function?
    A: Arrays must be passed by reference for the function to modify them.
  • Q3: What are the two main sorting order constants used with array_multisort()?
    A: SORT_ASC for ascending and SORT_DESC for descending.
  • Q4: Can array_multisort() be used to sort associative arrays by their values?
    A: It is generally used with indexed arrays; sorting associative arrays requires care or other methods.
  • Q5: What function can you use to extract a column from a multidimensional array before sorting?
    A: The array_column() function.

Mid-Level Questions

  • Q1: How can you sort a multidimensional array by multiple keys using array_multisort()?
    A: Extract arrays of keys using array_column() and then call array_multisort() with those arrays followed by the original array.
  • Q2: What is the purpose of the $sort_flags parameter in array_multisort()?
    A: It specifies how the sorting is performed, for example numeric sorting or string sorting.
  • Q3: What happens if the first array passed to array_multisort() contains duplicate values?
    A: The function sorts subsequent arrays accordingly, maintaining parallel order; second sorting criteria can be used to order duplicates.
  • Q4: Can array_multisort() sort arrays of different lengths? What issues can arise?
    A: It expects arrays of the same length; if lengths differ, some elements may be lost or not sorted properly.
  • Q5: How do you sort an array numerically and another array alphabetically in parallel using array_multisort()?
    A: Pass the numeric array with SORT_NUMERIC flag and string array with SORT_STRING, specifying the respective sort order.

Senior-Level Questions

  • Q1: Explain internally how array_multisort() maintains correlation between multiple arrays during sorting.
    A: It sorts the first array and rearranges all other arrays in the order that aligns with the sorted first array's keys to maintain relationships.
  • Q2: Why might you prefer usort() with a custom comparator over array_multisort() for complex multidimensional sorting?
    A: usort() allows custom logic per element, handling complex conditions; array_multisort() is limited to linear multi-array sorting by columns.
  • Q3: How does the sorting behavior differ when using SORT_REGULAR, SORT_NUMERIC, and SORT_STRING flags in array_multisort()?
    A: SORT_REGULAR sorts comparing values normally; SORT_NUMERIC treats values as numbers; SORT_STRING sorts values as strings lexicographically.
  • Q4: How can you handle sorting multidimensional associative arrays by value when keys may not align? Can array_multisort() handle this directly?
    A: array_multisort() requires aligned keys; to sort associative arrays by values, first extract columns or re-index arrays before sorting.
  • Q5: Discuss potential issues with sorting arrays that contain mixed data types using array_multisort().
    A: Mixed types can cause inconsistent comparisons, resulting in unpredictable order; casting or using proper $sort_flags can mitigate these issues.

FAQ

Q: Does array_multisort() return a sorted copy of arrays or sort them in place?
A: It sorts the arrays in place and returns a boolean true on success.
Q: Can array_multisort() sort arrays of objects?
A: Not directly. You must extract sortable properties into arrays and use those with array_multisort().
Q: How do I sort an associative array by keys with array_multisort()?
A: array_multisort() is designed mainly for value-based sorting. Use ksort() or uksort() for key-based sorting.
Q: Is array_multisort() stable? Meaning, does it preserve the order of equal elements?
A: Sorting stability isn't guaranteed with array_multisort(). For stable sorts, consider custom sorting with usort().
Q: Can I use array_multisort() to sort multiple arrays by descending and ascending orders at the same time?
A: Yes, by specifying the sort order flags for each array in the function arguments.

Conclusion

The PHP array_multisort() function is a versatile and efficient way to sort multiple arrays simultaneously and to sort multidimensional arrays by one or multiple keys. Understanding how to use the different parameters effectively enables advanced sorting workflows with clarity and precision.

By following best practices and avoiding common pitfalls outlined in this tutorial, you can harness the full power of array_multisort() in your PHP projects, especially when dealing with correlated datasets and complex sorting criteria.