PHP array multisort

Education is not limited to just classrooms. It can be gained anytime, anywhere... - Ravi Ranjan (M.Tech-NIT)

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.

Pictorial Presentation :

php-array-array_multisort()

Example - 1 :

  1.   

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

  3.   

  4. print_r($array1);  

  5.   

  6. print_r($array2);  

  7.   

  8. ?>  

  9.    

Output :

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

Example - 2 :

  1. <?php  
  2.   
  3. $array1 = array(array(1,"7",10,6,"Z"),array(100,20,"25",10,50));  
  4.   
  5. array_multisort($array1[0],SORT_ASC, SORT_STRING,$array1[1],SORT_NUMERIC, SORT_DESC);  
  6.   
  7. var_dump($array1);  
  8.   
  9. ?>  

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) } }