English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

PHP Basic Tutorial

PHP Advanced Tutorial

PHP & MySQL

PHP Reference Manual

PHP array_multisort() function usage and examples

PHP Array Function Manual

The PHP array_multisort() function sorts multiple arrays or multidimensional arrays

Syntax

array_multisort(array1,sorting order,sorting type,array2...);

Definition and usage

 array_multisort() can be used to sort multiple arrays at once, or to sort multidimensional arrays based on one or more dimensions.
The associated (string) key name remains unchanged, but the numeric key name will be reindexed.

Parameter

Serial numberParameters and descriptions
1

array1(required)

It specifies an array

2

sorting order (optional)

It specifies the sorting order. Possible values-

  • SORT_ASC Default. Arrange in ascending order (A-Z)

  • SORT_DESC Sort in descending order (Z-A)

3

sorting type (optional)

When comparing elements, it specifies the type to be used. Possible values:

  • SORT_REGULAR - Compare items by the usual method (without modifying the type)

  • SORT_NUMERIC - According to numerical size comparison

  • SORT_STRING - According to string comparison

  • SORT_LOCALE_STRING - Sort strings according to the current locale settings. It will use locale information, which can be modified through setlocale().

  • SORT_NATURAL - Sort strings by their 'natural order', similar to natsort()

  • SORT_FLAG_CASE - Can be combined (bitwise OR) SORT_STRING or SORT_NATURAL for case-insensitive string sorting.

4

array2(Optional)

It specifies an array

Return Value

Success, returns TRUE; failure, returns FALSE.

Online Example

1Multiple Arrays Sorting Example

<?php
   $input1 = array("10" 100, 100, "a");
   $input2 = array(1, 3",2" 1);
   
   array_multisort($input1, $input2);
   print_r($input1);
   print_r($input2);
?>
Test and See‹/›

Output Result:

Array
(
    [0] => 10
    [1=> a
    [2=> 100
    [3=> 100
)
Array
(
    [0] => 1
    [1=> 1
    [2=> 2
    [3=> 3
)

2Sorting Multi-dimensional Arrays Example

<?php
$ar = array(
       array("10" 11, 100, 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);
?>
Test and See ‹/›

Output Result:

array(2) {
  [0]=> array(5) {
    [0]=> string(2) "10"
    [1=> int(100)
    [2=> int(100)
    [3=> int(11)
    [4=> string(1) "a"
  }
  [1=> array(5) {
    [0]=> int(1)
    [1=> int(3)
    [2=> string(1) "2"
    [3=> int(2)
    [4=> int(1)
  }
}

3Case-insensitive Sorting of Arrays

<?php
$array = array('Alpha', 'atomic', 'Beta', 'bank');
$array_lowercase = array_map('strtolower', $array);
array_multisort($array_lowercase, SORT_ASC, SORT_STRING, $array);
print_r($array);
?>
Test and See ‹/›

Output Result:

Array
(
    [0] => Alpha
    [1=> atomic
    [2=> bank
    [3=> Beta
)

 PHP Array Function Manual