w3resource

PHP: array_multisort() function

PHP: Sort multiple or multi-dimensional arrays

The array_multisort() function is used to sort multiple arrays or a multidimensional array by one or more dimensions.

Note: Associative (string) keys will be maintained, but numeric keys will be re-indexed.

Version:

Syntax:

array_multisort(array_name1, sorting_order, sorting_type, array_name2, array_name3...) 

Parameters:

Name Description Required /
Optional
Type
array_name1 Specifies the array. Required Array
sorting_order Specifies the sorting order.
SORT_ASC - Sort in ascending order
SORT_DESC - Sort in descending order
Optional Mixed*
sorting_type Sets the sorting behavior.
Possible type :
SORT_REGULAR - Compare items normally.
SORT_NUMERIC - Compare items numerically.
SORT_STRING - Compare items as strings.
Optional Mixed*
array_name2,3.... More arrays. Optional Array

*Mixed: Mixed indicates that a parameter may accept multiple(but not necessarily all) types.

Return value

TRUE on success or FALSE on failure.

Value Type: Boolean.

Example - 1:

<?php

$array1 = array(1,7,10,6);$array2 = array(100,20,25,10);array_multisort($array1, $array2);

print_r($array1);

print_r($array2);

?>

Output:

Array ( [0] => 1 [1] => 6 [2] => 7 [3] => 10 ) Array ( [0] => 100 [1] => 10 [2] => 20 [3] => 25 ) 

View the example in the browser

Example - 2 :

<?php

$array1 = array(array(1,"7",10,6,"Z"),array(100,20,"25",10,50));

array_multisort($array1[0],SORT_ASC, SORT_STRING,$array1[1],SORT_NUMERIC, SORT_DESC);

var_dump($array1);

?>

Output :

array(2) {
  [0]=>
  array(5) {
    [0]=>
    int(1)
    [1]=>
    int(10)
    [2]=>
    int(6)
    [3]=>
    string(1) "7"
    [4]=>
    string(1) "Z"
  }
  [1]=>
  array(5) {
    [0]=>
    int(100)
    [1]=>
    string(2) "25"
    [2]=>
    int(10)
    [3]=>
    int(20)
    [4]=>
    int(50)
  }
}
 

View the example in the browser

Practice here online :

See also

PHP Function Reference

Previous: array_merge
Next: array_pad



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/php/function-reference/array_multisort.php