-->
Jump to Content
 

About the Author

spacer

Hi, I’m Chris, a web craftsman making things like Mapalong & Brooklyn Beta with my friends at Analog.


Sorting Multi-Dimensional Arrays in PHP

  • Thu, 30 Jun 2011 at 20:57:25 GMT
  • 13 comments
  • tweets

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 at 20:57:25 GMT. Follow me on Twitter.

  • spacer Twitter
  • spacer Hacker News
  • spacer Delicious
  • spacer Reddit

13 comments

1.spacer 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.spacer 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.spacer Avi Block said:

Or just use ruby......

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


4.spacer 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.spacer 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.spacer 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.spacer 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.spacer Nick Yahnke said:

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

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


9.spacer 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.spacer 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.spacer 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.spacer 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.spacer David Authier said:

Thanks for the tip ! :)

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


Hello! What’s your name?

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

  • Previous Post
  • Blog History
  • Next Post

Feeds

  • Blog (6412 readers)
  • Twitter

Ads via Carbon

Planet

Unstructured data is worth the effort when you've got the right tools
from O'Reilly Radar
Fluid grids, orientation resolution independence
from Jeffrey Zeldman
Four short links: 7 February 2012
from O'Reilly Radar
Building The Ecosystem
from Fred Wilson
Speaking at DayCamp for Developers
from Lorna Mitchell
End users adapting tablets for specific business needs
from Jonathan Stark
Relative Date Ranges: Current Week of Prior Year
from Timothy Boronczyk

Explore the Planet

Fresh Links

  1. Accept-Charset Is No More
  2. Twitter ♥ Open Source
  3. A Beginners Guide to HTML & CSS
  4. Kern And Burn
  5. Git Immersion
  6. Eloquent JavaScript
  7. Switch to OSM
  8. The Science of Magic Series
  9. CartoDB
  10. HandBrake Batch

Explore Links


Popular Posts

PHP Session Debugging
  • 25 Mar 2011
  • 9 Comments
Ideas of March
  • 15 Mar 2011
  • 34 Comments
JavaScript and URLs
  • 28 Feb 2011
  • 31 Comments
Twitter OAuth
  • 16 Sep 2010
  • 10 Comments
Auto Increment with MongoDB
  • 29 Jul 2010
  • 14 Comments

Popular Articles

Cross-Site Request Forgeries
  • 13 Dec 2004
  • 77 Comments
The Truth about Sessions
  • 15 Dec 2003
  • 79 Comments
Foiling Cross-Site Attacks
  • 14 Oct 2003
  • 69 Comments
Storing Sessions in a Database
  • 14 Dec 2004
  • 62 Comments
How to Avoid “Page Has Expired” Warnings
  • 21 Oct 2004
  • 48 Comments

Work and Books

spacer spacer spacer

  • Analog A web design and development co-operative
  • Essential PHP Security O'Reilly, 2005
  • HTTP Developer's Handbook Sams, 2003

gipoco.com is neither affiliated with the authors of this page nor responsible for its contents. This is a safe-cache copy of the original web site.