array_multisort() function in PHP


The array_multisort() function sorts multiple or multi-dimensional arrays. It returns a sorted array.

Syntax

array_multisort(arr1, sort_order, sort_type, arr2, arr3, arr4...)

Parameters

  • arr1 − Array to be sorted

  • sort_order − The sort order. The following are the possible values

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

    • - SORT_DESC - Sort in descending order (Z-A)

  • sort_type − The sort behavior. Following are the possible values

    • SORT_REGULAR - Default. Compare elements normally (Standard ASCII)

    • SORT_NUMERIC - Compare elements as numeric values

    • SORT_STRING - Compare elements as string values

    • SORT_LOCALE_STRING - Compare elements as string, based on the current locale (can be changed using setlocale())

    • SORT_NATURAL - Compare elements as strings using "natural ordering" like natsort()

    • SORT_FLAG_CASE - Can be combined (bitwise OR) with SORT_STRING or SORT_NATURAL to sort strings case-insensitively.

  • arr2 − Another array. Optional

  • arr3 − Another array. Optional.

  • arr4 − Another array. Optional.

Return

The array_multisort() function returns a sorted array.

Example

 Live Demo

<?php
$a1 = array(12, 55, 3, 9, 99);
$a2 = array(44, 67, 22, 78, 46);
array_multisort($a1,$a2);
print_r($a1);
print_r($a2);
?>

Output

Array
(
[0] => 3
[1] => 9
[2] => 12
[3] => 55
[4] => 99
)
Array
(
[0] => 22
[1] => 78
[2] => 44
[3] => 67
[4] => 46
)

Example

Let us see another example to merge two array and sort them in ascending order.

 Live Demo

<?php
$a1 = array(12, 55, 3, 9, 99);
$a2 = array(44, 67, 22, 78, 46);
$num = array_merge($a1,$a2);
array_multisort($num,SORT_ASC,SORT_NUMERIC);
print_r($num);
?>

Output

Array
(
[0] => 3
[1] => 9
[2] => 12
[3] => 22
[4] => 44
[5] => 46
[6] => 55
[7] => 67
[8] => 78
[9] => 99
)

Updated on: 23-Dec-2019

128 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements