Content · Programming · PHP

PHP array_multisort() Function: Usage and Examples

Learn how to use PHP array_multisort() to sort multiple arrays together, apply ascending and descending order, and sort multidimensional arrays by multiple fields.

2 views Published Oct 16, 2026 Updated Oct 16, 2026 Admin

Sorting a PHP array is straightforward, but what happens when you need to sort several related arrays together or organize records by more than one field?

The array_multisort() function solves this problem. It can sort multiple arrays while keeping their corresponding elements together, or sort multidimensional records by selected columns.

What Is array_multisort() in PHP?

The array_multisort() function sorts one or more arrays using specified sorting rules.

Its syntax is:

array_multisort(
    array &$array1,
    mixed $array1_sort_order = SORT_ASC,
    mixed $array1_sort_flags = SORT_REGULAR,
    mixed ...$rest
): true

The main arguments are:

  • $array1 — The first array to sort.
  • $array1_sort_order — Ascending or descending order.
  • $array1_sort_flags — How values should be compared.
  • ...$rest — Additional arrays and their optional sorting rules.

Unlike many other array functions, array_multisort() modifies the supplied arrays directly. It does not return a new sorted array.

The function returns true on successful execution. Its return type was formally changed from bool to true in PHP 8.5.

Example 1: Sorting Multiple Arrays Together

Imagine you have one array containing product prices and another containing product names.

<?php

$prices = [50, 20, 80];
$names = ["Keyboard", "Mouse", "Monitor"];

array_multisort(
    $prices,
    SORT_ASC,
    SORT_NUMERIC,
    $names
);

foreach ($names as $index => $name) {
    echo $name . ": $" . $prices[$index] . PHP_EOL;
}

Output:

Mouse: $20
Keyboard: $50
Monitor: $80

The prices are sorted from lowest to highest. The product names are rearranged to maintain their relationship with the prices.

This makes array_multisort() useful when several arrays represent different columns of the same dataset.

Example 2: Sorting in Descending Order

Use SORT_DESC to sort values from highest to lowest.

<?php

$scores = [75, 95, 60, 85];

array_multisort(
    $scores,
    SORT_DESC,
    SORT_NUMERIC
);

print_r($scores);

Output:

Array
(
    [0] => 95
    [1] => 85
    [2] => 75
    [3] => 60
)

The most commonly used sorting options are:

Constant Purpose
SORT_ASC Ascending order (default).
SORT_DESC Descending order.
SORT_REGULAR Normal PHP value comparison (default).
SORT_NUMERIC Numeric comparison.
SORT_STRING String comparison.
SORT_NATURAL Natural string ordering, such as File2 before File10.

For case-insensitive ASCII string sorting, you can combine SORT_STRING | SORT_FLAG_CASE.

Sorting by Multiple Criteria

When the first array contains duplicate values, the next array acts as a secondary sorting criterion.

For example, let's sort tickets by priority first and then by ticket ID.

<?php

$priorities = [2, 1, 2];
$ticketIds = ["T-3", "T-2", "T-1"];

array_multisort(
    $priorities,
    SORT_ASC,
    SORT_NUMERIC,
    $ticketIds,
    SORT_ASC,
    SORT_STRING
);

foreach ($ticketIds as $index => $id) {
    echo $id . ": " . $priorities[$index] . PHP_EOL;
}

Output:

T-2: 1
T-1: 2
T-3: 2

Priority determines the primary order. When two tickets have the same priority, their IDs determine the order between them.

If all sorting criteria compare as equal, PHP 8.0 and later preserve the original relative order of those elements.

Practical Example: Sorting Products by Price and Name

Most applications store products as an array of records rather than separate arrays.

You can use array_column() to extract sorting fields, then pass those fields alongside the original records to array_multisort().

Create a file named sort-products.php:

<?php

declare(strict_types=1);

$products = [
    ["name" => "Webcam", "price" => 49.99],
    ["name" => "Mouse", "price" => 19.99],
    ["name" => "Keyboard", "price" => 49.99],
    ["name" => "Monitor", "price" => 89.99]
];

// Extract the sorting columns.

$prices = array_column($products, "price");
$names = array_column($products, "name");

// Sort by price, then by product name.

array_multisort(
    $prices,
    SORT_ASC,
    SORT_NUMERIC,
    $names,
    SORT_ASC,
    SORT_STRING,
    $products
);

// Display the sorted records.

echo "<h2>Products by Price</h2>";
echo "<ul>";

foreach ($products as $product) {

    $message = $product["name"]
        . " - $"
        . number_format($product["price"], 2);

    echo "<li>" . htmlspecialchars(
        $message,
        ENT_QUOTES,
        "UTF-8"
    ) . "</li>";
}

echo "</ul>";

Browser output:

Products by Price

Mouse - $19.99
Keyboard - $49.99
Webcam - $49.99
Monitor - $89.99

Products are sorted by ascending price. Because Keyboard and Webcam have identical prices, their names determine their relative order.

The original product records remain intact, but their order changes. This is useful when preparing product catalogs, reports, and other structured datasets for display.

Important Behaviors and Common Mistakes

There are several details to remember when using array_multisort():

  • Arrays are modified: The supplied arrays are reordered directly. Make copies first if you need to preserve the original order.
  • Array lengths must match: All arrays supplied to the same call must contain the same number of elements. PHP 8+ throws a ValueError when their sizes differ.
  • Numeric keys are reindexed: Integer keys are reassigned sequentially, starting at zero.
  • String keys are preserved: Associative keys remain associated with their corresponding elements.
  • Sorting order matters: Later arrays act as tie-breakers when earlier arrays contain equal values.
  • The internal pointer changes: The function resets each sorted array's internal pointer to its first element.

Because the function modifies its arguments, pass variables containing arrays rather than assuming it will produce a sorted array as its return value.

array_multisort() vs Other Sorting Functions

Function Best Used For
sort() Sorting one array by values in ascending order.
rsort() Sorting one array by values in descending order.
asort() Sorting values while preserving array keys.
usort() Sorting an array using a custom comparison callback.
array_multisort() Sorting multiple related arrays or records by several fields.

Choose array_multisort() when you need column-based sorting or multiple sorting criteria. For complex record-specific comparison logic, usort() may be easier to maintain.

Key Takeaways

  • array_multisort() sorts multiple arrays together while keeping corresponding elements aligned.
  • It supports ascending, descending, numeric, and string sorting.
  • Additional arrays can provide secondary sorting criteria.
  • Use array_column() to sort multidimensional records by selected fields.
  • The function modifies the supplied arrays rather than returning sorted copies.
  • Numeric keys are reindexed, while string keys are preserved.

The array_multisort() function is particularly useful when sorting related datasets by multiple criteria. Understanding how it coordinates arrays and handles keys makes it easier to organize structured data without writing custom sorting algorithms.

For additional information, see the official PHP array_multisort() documentation.

Share this resourceSend this page to someone who may find it useful.