PHP array_multisort() Function: Sorting Multiple Arrays or Multidimensional Arrays

array_multisort() is a PHP function that enables sorting of multiple arrays or multidimensional arrays simultaneously, supporting various sort orders and types, with detailed syntax, parameter explanations, and example code illustrating its usage and output.

Laravel Tech Community
Laravel Tech Community
Laravel Tech Community
PHP array_multisort() Function: Sorting Multiple Arrays or Multidimensional Arrays

array_multisort() can be used to sort multiple arrays at once, or to sort a multidimensional array based on one or more dimensions.

String keys remain unchanged, while numeric keys are re‑indexed.

Sorting order flags:

SORT_ASC – ascending order

SORT_DESC – descending order

Sorting type flags:

SORT_REGULAR – standard comparison

SORT_NUMERIC – numeric comparison

SORT_STRING – string comparison

Each array can have only one sorting flag; default flags are SORT_ASC and SORT_REGULAR.

The input arrays are treated as columns of a table and sorted by rows, similar to SQL’s ORDER BY clause. The first array is the primary sort key; if values are equal, subsequent arrays are used.

Function signature:

bool array_multisort(array &$arr, mixed $arg = SORT_ASC, ...)

Parameters:

arr : The array to be sorted.

arg : Additional arrays or sorting flag constants (SORT_ASC, SORT_DESC, SORT_REGULAR, SORT_NUMERIC, SORT_STRING).

... : Additional array variables for recursive merging.

Return value: TRUE on success, FALSE on failure.

Example:

<?php
$ar = array(
    array("10", 11, 100, "a"),
    array(1, 2, "2", 3, 1)
);
array_multisort($ar[0], SORT_ASC, SORT_STRING, $ar[1], SORT_NUMERIC, SORT_DESC);
var_dump($ar);
?>

Output:

array(2) {
  [0]=>
  array(5) {
    [0]=>
    string(2) "10"
    [1]=>
    int(11)
    [2]=>
    int(100)
    [3]=>
    string(1) "a"
    [4]=>
    int(1)
  }
  [1]=>
  array(5) {
    [0]=>
    int(5)
    [1]=>
    int(4)
    [2]=>
    int(3)
    [3]=>
    int(2)
    [4]=>
    int(1)
  }
}
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.

Backend DevelopmentSortingarray_multisortmultidimensional arrays
Laravel Tech Community
Written by

Laravel Tech Community

Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.

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.