Return an array sorted in ascending order.
<?php $a=array(“Dog”,“Cat”,“Horse”,“Bear”,“Zebra”); array_multisort($a); print_r($a); ?> |
The array_multisort() function returns a sorted array. You can provide one or more arrays as input. The function sorts the first array, then sorts the following arrays based on the order of the first array. If there are duplicate values, it continues sorting using the subsequent arrays.
Note: String keys will be preserved, but numeric keys will be re-indexed starting from 0 and incrementing by 1.
Note: You can specify the sort order and sort type parameters for each array. If not provided, default values are used for each array parameter.
array_multisort(array1, sortorder, sorttype, array2, array3, …) |
Parameter |
Description |
array1 |
Required. Provides an array. |
sortorder |
Optional. Defines the sorting order. Possible values:
|
sorttype |
Optional. Specifies the type of comparison for elements. Possible values include:
SORT_FLAG_CASE can be combined (using bitwise OR) with SORT_STRING or SORT_NATURAL to sort strings in a case-insensitive manner. |
array2 |
Optional. Defines an array. |
array3 |
Optional. Indicates an array. |
Return Value: |
Returns TRUE on success or FALSE on failure. |
PHP Version: |
4+ |
PHP Changelog: |
PHP 5.4 introduced the sorting types SORT_NATURAL and SORT_FLAG_CASE. PHP 5.3 introduced the sorting type SORT_LOCALE_STRING. |
Return an array sorted in ascending order:
<?php $a1=array(“Dog”,“Cat”); $a2=array(“Fido”,“Missy”); array_multisort($a1,$a2); print_r($a1); print_r($a2); ?> |
Observe how the sorting behaves when two values are identical:
<?php $a1=array(“Dog”,“Dog”,“Cat”); $a2=array(“Pluto”,“Fido”,“Missy”); array_multisort($a1,$a2); print_r($a1); print_r($a2); ?> |
Utilizing sorting parameters:
<?php $a1=array(“Dog”,“Dog”,“Cat”); $a2=array(“Pluto”,“Fido”,“Missy”); array_multisort($a1,SORT_ASC,$a2,SORT_DESC); print_r($a1); print_r($a2); ?> |
Combine two arrays and sort them numerically in descending order:
<?php $a1=array(1,30,15,7,25); $a2=array(4,30,20,41,66); $num=array_merge($a1,$a2); array_multisort($num,SORT_DESC,SORT_NUMERIC); print_r($num); ?> |