A multidimensional array is an array containing one or more arrays. In other words, a multidimensional array is an array which stores another array at each index rather than storing a single value.

Thanks to sort() & ksort() function that makes the sorting of arrays really easy in php. Using them we can sort one-dimensional array by key, by value, in reverse order, and so forth. But these function will not work on multidimensional arrays (not as you’d probably like, at least). To sort a multidimensional array, you define your own sort function and then tell PHP to use that function by invoking the built-in usort(), uasort() or uksort() function.

1. Defining a multidimensional array

$player = array(
        256 => array('name' => 'Cristiano Ronaldo', 'age' => 34),
        6 => array('name' => 'Lionel Messi', 'age' => 31),
        364 => array('name' => 'Luis Suarez', 'age' => 32),
        68 => array('name' => 'Neymar', 'age' => 27),
        2 => array('name' => 'Mohamed Salah', 'age' => 26),
    );

The outer array, $player, has five elements, each of which is also an array. The inner arrays use the player ID for the key(a random made-up value) and store two pieces of data: the player’s name and their age.

2. Defining the name sorting function

//Name Sorting Function:
    function name_sort($x, $y){
        return strcasecmp($x['name'], $y['name']);
    }

The strcasecmp() function returns a number negative, 0, or positive indicating how similar two strings are. If a negative value is returned, the first string comes before the second alphabetically, if a positive value is returned, the second string comes first, if 0 is returned, the strings are the same.

3. Defining the age sorting function

//age Sorting Function:
//Sort in Descending Order:
    function age_sort($x, $y){
        return ($x['age'] < $y['age']);
    }

This function should perform a descending sort, listing the highest age first. This can be easily accomplished by changing the comparison operator from greater than to less than. Thus if the first argument is less than the second, the value true is returned, which indicates the second argument should come first in the ordered list.

4. Printing the array

4.1 Printing the array as is

// Print the array as is:
    echo '<h2> Array As Is </h2><pre>' . print_r($player, 1) . '</pre>';

Use the print_r() function to quickly print out the array’s content. To improve the readability, the output will be wrapped within <pre> tags.

4.2 Printing the array sorted by name

//Sort By name:
    uasort($player, 'name_sort');
    echo '<h2> Array Sorted By Name </h2><pre>' . print_r($player, 1) . '</pre>';

The usort() function sorts by values but does not maintain the keys. When you use uasort(), the keys will be maintained. Therefore, the uasort() function is used so that the keys ( the player IDs ) are not lost. The sorting will drop the keys if usort() was invoked.

Array Sorting By Name - Using uasort()
Array Sorted By name Using uasort()
Array Sorting By Name - Using usort()
Array Sorted By name Using usort()

4.3 Printing the array sorted by age

//Sort By age:
    uasort($player, 'age_sort');
    echo '<h2> Array Sorted By age </h2><pre>' . print_r($player, 1) . '</pre>';

Printing the array sorted by age is similar as printing the array sorted by name.

Now, save the file, place it in your Web Directory, and test in your Web Browser.

Here is the full code that we have written during this tutorial.

<!Doctype html>
<html lang="en">
<head>
    <meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
    <title>Sorting Multidimensional Arrays</title>
</head>
<body>
    <?php 

    // Let's create the array
    $player = array(
        256 => array('name' => 'Cristiano Ronaldo', 'age' => 34),
        6 => array('name' => 'Lionel Messi', 'age' => 31),
        364 => array('name' => 'Luis Suarez', 'age' => 32),
        68 => array('name' => 'Neymar', 'age' => 27),
        2 => array('name' => 'Mohamed Salah', 'age' => 26),
    );

    //Name Sorting Function:
    function name_sort($x, $y){
        return strcasecmp($x['name'], $y['name']);
    }

    //age Sorting Function:
    //Sort in Descending Order:
    function age_sort($x, $y){
        return ($x['age'] < $y['age']);
    }

    // Print the array as is:
    echo '<h2> Array As Is </h2><pre>' . print_r($player, 1) . '</pre>';

    //Sort By name:
    uasort($player, 'name_sort');
    echo '<h2> Array Sorted By Name  </h2><pre>' . print_r($player, 1) . '</pre>';

    //Sort By age:
    uasort($player, 'age_sort');
    echo '<h2> Array Sorted By age </h2><pre>' . print_r($player, 1) . '</pre>';

    ?>
</body>

</html>

CONCLUSION

In this tutorial, we learned how can we sort the the multidimensional array using the user defined comparison function.

If this tip has been helpful to you, please spend a second of your time and share it using the buttons below… thanks!

Leave a Reply

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