PHP array_multisort | Sort Multiple or Multidimensional Array

PHP array_multisort is an inbuilt sort Function in PHP. It sorts multiple arrays at once or multi-dimensional arrays. Although it maintains string keys of an Associative Array, it re-indexes all the numerical keys. In this article, we will discuss the PHP array_multisort Function. Also, we will discuss a few examples of using it.

Syntax

array_multisort($array1, $sortingOrder, $sortingType, $array2 … );

Parameters

You can pass multiple parameters in the PHP array_multisort Function. The description of the parameters is as follows:

  • $array: The first mandatory parameter is the array you want to sort.
  • $sortingOrder: The order for sorting the previous array argument. It is an optional parameter. You can even omit it completely or swap with the third parameter. It expects two values:
    • SORT_ASC: Sort Array in Ascending Order. (Default)
    • SORT_DESC: Sort Array in Descending Order.
  • $sortFlag: The function provides 6 sorting types which are optional to pass. This parameter can take the following values:
    • SORT_REGULAR: Compares the elements normally without changing their type.
    • SORT_NUMERIC: Compares the elements numerically.
    • SORT_STRING: Compares the elements string-wise.
    • SORT_LOCALE_STRING: Compares the elements as a string based on current locale on passing.
    • SORT_NATURAL: Compares the elements as strings using natural ordering.
    • SORT_FLAG_CASE: Compares the elements as case-insensitive strings. Also, this parameter can be used | (bitwise) with SORT_NATURAL or SORT_STRING.

Additionally, you can pass multiple arrays with sort order and flags.

Return Value

The function returns true on success and false on failure. Additionally, it sorts the original input arrays in the given order.

Examples

Let’s discuss a few examples of using the PHP array_multisort Function.

Example 1: Sorting Multiple Arrays

For instance, consider two simple arrays.

<?php
	$array1 = array(20, 10, 50, 30);
	$array2 = array(1, 3, 2, 4);
	array_multisort($array1, $array2);

	print_r($array1);
        //The first array is sorted in ascending order
	/*
	Array
	(
	    [0] => 10
	    [1] => 20
	    [2] => 30
	    [3] => 50
	)
	*/
	print_r($array2);
        //The elements in the second array are sorted according to the corresponding keys in the first array
	/*
	Array
	(
	    [0] => 3 (10 from First Array)
	    [1] => 1 (20 from First Array)
	    [2] => 4 (30 from First Array)
	    [3] => 2 (50 from First Array)
	)
	*/
?>

In the above example, you can observe that the first array is finally 10, 20, 30, 50. However, it is important to note the sorting order of the second array. The function sorts the elements of the second array according to the initial order of the first array. In other words, the elements in the second array corresponding to the identical entries in the first array are sorted as well.

Example 2: Sort Multi-Dimensional Array

For example, consider a multi-dimensional array.

<?php
	$array = array(
    	array("10", 11, 200, 200, "a"),
       	array(   1,  5, "5",   3,   1)
	);
	array_multisort($array[0], SORT_ASC, SORT_STRING,
	                $array[1], SORT_NUMERIC, SORT_DESC);
	print_r($array);
	/*
	Array
	(
	    [0] => Array
	        (
	            [0] => 10
	            [1] => 11
	            [2] => 200
	            [3] => 200
	            [4] => a
	        )
	    [1] => Array
	        (
	            [0] => 1
	            [1] => 5
	            [2] => 5
	            [3] => 3
	            [4] => 1
	        )
	)
	*/
?>

In this example, after sorting, the first array will transform to “10”, 11, 200, 200, “a” (it was sorted as strings in ascending order). The second will contain 1, 5, “5”, 3, 1 (sorted as numbers, in descending order).

Example 3: Sorting Multiple Rows

For instance, let’s consider the following data to be sorted using PHP array_multisort Function. The data consists of multiple rows in a table.

<?php
$data[] = array('score' => 67, 'priority' => 2);
$data[] = array('score' => 86, 'priority' => 1);
$data[] = array('score' => 85, 'priority' => 6);
$data[] = array('score' => 98, 'priority' => 2);
$data[] = array('score' => 86, 'priority' => 6);
$data[] = array('score' => 67, 'priority' => 7);
?>

Suppose we want to sort the array in decreasing score and increasing priority. In other words, the rows with larger score will appear first. However, if two scores are equal, the one with lower priority will come first. You can do this by using the PHP array_multisort Function.

Since, array_multisort requires an array of columns to sort, we fetch the column values of the array using PHP array_column Function.

//Fetch the columns score and priority
$score  = array_column($data, 'score'); //Array ( [0] => 67 [1] => 86 [2] => 85 [3] => 98 [4] => 86 [5] => 67 )
$priority = array_column($data, 'priority'); //Array ( [0] => 2 [1] => 1 [2] => 6 [3] => 2 [4] => 6 [5] => 7 )

// Sort the data with score descending, priority ascending
// Add $data as the last parameter, to sort by the common key
array_multisort($score, SORT_DESC, $priority, SORT_ASC, $data);

?>

After sorting, the data will look like this:

score  | priority
-------+--------
98 | 2
86 | 1
86 | 6
85 | 6
67 | 2
67 | 7

Conclusion

In conclusion, we discussed the PHP array_multisort Function. It can sort multiple arrays at once or multi-dimensional arrays. Also, it is very helpful in sorting arrays on multiple keys. You can learn more about on the PHP Official Documentation. Also, you can learn about more PHP Array Functions on Concatly.

.

Spread the Knowledge

Leave a Reply

Your email address will not be published. Required fields are marked *