How to Use the PHP array_multisort() Function



In this article, you will learn how to use the PHP array_multisort() function.

PHP array_multisort() Function

The array_multisort() function in PHP is used to sort multiple arrays, or an array of arrays, in a specified order.

The array_multisort function in PHP can sort multiple arrays by using the values of one of the arrays as a key. The other arrays will be sorted in the same order as the array used as a key. You can also specify the sort order for each array by using SORT_ASC for ascending order or SORT_DESC for descending order.

array_multisort(array1, sorter1 [, sorter2 [, ... [, arrayn [, sorter1 [, sorter2 [, ...]]]]]]);
  • array1, array2, …, arrayn: The arrays you want to sort.
  • sorter1, sorter2, …: The sorting order for each array. Specify SORT_ASC for ascending order, SORT_DESC for descending order.

You can sort two arrays $fruits and $prices by the values in $prices. The $fruits array will be sorted in the same order as $prices, so that the keys in both arrays remain associated:

  $fruits = array("d" => "lemon", "a" => "orange", "b" => "banana", "c" => "apple");
  $prices = array("d" => 1, "a" => 4, "b" => 2, "c" => 3);
  array_multisort($prices, SORT_ASC, $fruits, SORT_ASC);

After the sort, $prices will be sorted in ascending order and $fruits will be sorted in the same order:

  $prices = array(1, 2, 3, 4);
  $fruits = array("lemon", "banana", "apple", "orange");

Note that if you have arrays with different keys, the array_multisort function will only sort the values with matching keys. The values with unmatched keys will be left unchanged.