Curriculum
Course: PHP Basic
Login

Curriculum

PHP Basic

PHP Install

0/1

PHP Casting

0/1

PHP Constants

0/1

PHP Magic Constants

0/1

PHP Operators

0/1

PHP Reference

0/276
Text lesson

array_multisort()

Example

Return an array sorted in ascending order.

<?php
$a=array(“Dog”,“Cat”,“Horse”,“Bear”,“Zebra”);
array_multisort($a);
print_r($a);
?>

Definition and Usage

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.

Syntax

array_multisort(array1, sortorder, sorttype, array2, array3, …)

Parameter Values

Parameter

Description

array1

Required. Provides an array.

sortorder

Optional. Defines the sorting order. Possible values:

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

sorttype

Optional. Specifies the type of comparison for elements. Possible values include:

  • 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 strings based on the current locale (modifiable with setlocale()).
  • SORT_NATURAL – Compare elements as strings using “natural ordering,” similar to natsort().

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.

Technical Details

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.

More Examples

Example

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);
?>

Example

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);
?>

Example

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);
?>

Example

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);
?>