About the Author

Chris Shiflett

Hi, I’m Chris: web craftsman, community leader, husband, father, and partner at Fictive Kin.


Sorting Multi-Dimensional Arrays in PHP

Every time I need to sort a multi-dimensional array in PHP, I have to look it up. It's not quite as quick and easy to look up as most things, so I'm going to blog a quick example.

Here's a simple array of users:

<?php
 
$users = array();
 
$users[] = array('username' => 'shiflett', 'name' => 'Chris Shiflett');
$users[] = array('username' => 'dotjay', 'name' => 'Jon Gibbins');
$users[] = array('username' => 'a', 'name' => 'Andrei Zmievski');
 
?>

There are a few different ways to create this array. Here's the output of print_r($users), so you clearly understand the structure:

Array
(
    [0] => Array
        (
            [username] => shiflett
            [name] => Chris Shiflett
        )
 
    [1] => Array
        (
            [username] => dotjay
            [name] => Jon Gibbins
        )
 
    [2] => Array
        (
            [username] => a
            [name] => Andrei Zmievski
        )
 
)

If I want to sort by username, I first create a separate array of usernames:

<?php
 
$usernames = array();
 
foreach ($users as $user) {
    $usernames[] = $user['username'];
}
 
?>

I then use array_multisort():

<?php
 
array_multisort($usernames, SORT_ASC, $users);
 
?>

Here's the output of print_r($users) after sorting by username:

Array
(
    [0] => Array
        (
            [username] => a
            [name] => Andrei Zmievski
        )
 
    [1] => Array
        (
            [username] => dotjay
            [name] => Jon Gibbins
        )
 
    [2] => Array
        (
            [username] => shiflett
            [name] => Chris Shiflett
        )
 
)

To sort the array by name instead, I'd do something very similar:

<?php
 
$names = array();
 
foreach ($users as $user) {
    $names[] = $user['name'];
}
 
array_multisort($names, SORT_ASC, $users);
 
?>

Here's the output of print_r($users) after sorting by name:

Array
(
    [0] => Array
        (
            [username] => a
            [name] => Andrei Zmievski
        )
 
    [1] => Array
        (
            [username] => shiflett
            [name] => Chris Shiflett
        )
 
    [2] => Array
        (
            [username] => dotjay
            [name] => Jon Gibbins
        )
 
)

There are many more uses of array_multisort(), and there are many other useful sorting functions. Please feel free to share some of your favorites in the comments.

Update: If your array isn't too big, and especially if you find it easier to understand, you might prefer usort(). Thanks to Franco Zeoli for this example:

<?php
 
// Sort the array by username.
usort($users, function ($a, $b) {
                  return strcmp($a['username'], $b['username']);
              });
 
?>

If your array is large, or you're concerned about performance, make sure you read Jordi Boggiano's comment.

About this post

Sorting Multi-Dimensional Arrays in PHP was posted on Thu, 30 Jun 2011. If you liked it, follow me on Twitter or share:

18 comments

1.Franco Zeoli said:

usort($users,  function ($a, $b) {
 
    return strcmp($a['username'], $b['username']);
 
});

I like it that way.

Fri, 01 Jul 2011 at 02:38:38 GMT Link


2.John Campbell said:

Now that php has first class functions, there is no reason not to use usort(). array_multisort() should probably be deprecated. People coming from pretty much any language are likely to understand usort, but I am baffled by array_multisort.

Fri, 01 Jul 2011 at 03:27:39 GMT Link


3.Avi Block said:

Or just use ruby......

Fri, 01 Jul 2011 at 06:13:26 GMT Link


4.Rolands Atvars said:

I would vote for usort() as well, because I think that it's more readable and just by glancing at it you can tell what it does (especially with closures). + it's shorter as well.

Fri, 01 Jul 2011 at 09:52:14 GMT Link


5.Nils Luxton said:

+1 for usort(), particularly with closures; it also allows more complex sorting rules without losing clarity.

Fri, 01 Jul 2011 at 10:06:19 GMT Link


6.Jordi Boggiano said:

I agree that usort() is more readable and convenient, but don't forget that it means many many function calls if you have a big array.

Function calls being a bit expensive in php, I think it's interesting to keep the array_multisort trick in your sleeve for performance-critical areas. And it should certainly not be deprecated.

Fri, 01 Jul 2011 at 11:10:51 GMT Link


7.Jim Gaudet said:

I can never remember this either, saved... I'm guess you will update this post with the usort example.

Fri, 01 Jul 2011 at 11:36:15 GMT Link


8.Nick Yahnke said:

http://php.net/manual/en/function.usort.php

Fri, 01 Jul 2011 at 13:41:41 GMT Link


9.Jeroen Fiege said:

I usually use this function (I found this functions somewhere on the internet years ago, credits go to the original author):

/*
 
 * sort a multi demensional array on a column
 
 *
 
 * @param array $array array with hash array
 
 * @param mixed $column key that you want to sort on
 
 * @param enum $order asc or desc
 
 */
 
function array_qsort2 (&$array, $column=0, $order="ASC") {
 
    $oper = ($order == "ASC")?">":"<";
 
    if(!is_array($array)) return;
 
    usort($array, create_function('$a,$b',"return (\$a['$column'] $oper \$b['$column']);")); 
 
    reset($array);
 
}

You can use it like this:

array_qsort2($users, "username", "ASC");

Fri, 01 Jul 2011 at 15:06:25 GMT Link


10.Joel Caton said:

Chris, Thanks for posting this and thanks to Franco and Jordi for their comments. The great thing about PHP is the many options we have to get tasks like this done as shown here.

Sat, 02 Jul 2011 at 06:15:03 GMT Link


11.Wil Moore said:

I personally prefer the following which is quite readable in my opinion and should scale well also:

<?php 
 
$users[] = array('username' => 'shiflett',  'name' => 'Chris Shiflett');
 
$users[] = array('username' => 'dotjay',    'name' => 'Jon Gibbins');
 
$users[] = array('username' => 'a',         'name' => 'Andrei Zmievski');
array_multisort(array_map(function($user){
 
    return $user['username'];
 
}, $users), SORT_ASC, $users);
 
 
 
var_dump($users);

Also, this way, there is only one global variable floating around (vs. the foreach since PHP has no block scope).

Sun, 03 Jul 2011 at 06:23:34 GMT Link


12.Michael Noga said:

I've used usort but have noticed perfomance issues with very large arrays, so I tend to still use array_multisort (in a very similar fasion to how Will showed his usage) to be safe.

Thu, 14 Jul 2011 at 19:47:46 GMT Link


13.David Authier said:

Thanks for the tip ! :)

Tue, 06 Dec 2011 at 10:45:55 GMT Link


14.Butch Ewing said:

You just saved me hours of testing and debugging. Thanks!

Tue, 21 Feb 2012 at 17:14:40 GMT Link


15. said:

Thanks,

you saved me hours of time

Tue, 03 Apr 2012 at 07:08:27 GMT Link


16.Karl Barnes said:

There is a great deal of information on usort and array_multisort but your example made their usage crystal clear - thanks!

Mon, 18 Jun 2012 at 22:52:40 GMT Link


17.Maria Antonietta said:

Thank you very much Chris!

You avoided me hours of headaches!

Tue, 10 Feb 2015 at 11:38:41 GMT Link


18.atif said:

A very good post with the use of multisort function. To read other basic types of sorting functions visit Blog of Cloudways.

Tue, 24 Nov 2015 at 11:12:04 GMT Link


Hello! What’s your name?

Want to comment? Please connect with Twitter to join the discussion.