Take the 2-minute tour ×

This question already has an answer here:

I have CSV data loaded into a multidimensional array. In this way each "row" is a record and each "column" contains the same type of data. I am using the function below to load my CSV file.

function f_parse_csv($file, $longest, $delimiter)
  $mdarray = array();
  $file    = fopen($file, "r");
  while ($line = fgetcsv($file, $longest, $delimiter))
    array_push($mdarray, $line);
  return $mdarray;

I need to be able to specify a column to sort so that it rearranges the rows. One of the columns contains date information in the format of Y-m-d H:i:s and I would like to be able to sort with the most recent date being the first row.

share|improve this question

marked as duplicate by deceze Jul 25 at 14:28


(2 yrs later...) If you're sorting dates stored as strings, you may first need to use strtotime [1] docs.php.net/manual/en/function.strtotime.php –  Dan Burton May 19 '10 at 18:33
Thanks for adding that link as an additional reference. –  Melikoth Feb 21 '13 at 15:12

12 Answers 12

up vote 123 down vote accepted

You can use array_multisort()

Try something like this:

foreach ($mdarray as $key => $row) {
    $dates[$key]  = $row[0]; 
    // of course, replace 0 with whatever is the date field's index

array_multisort($dates, SORT_DESC, $mdarray);
share|improve this answer
I think this shows me why I couldn't get array_multisort to work before. –  Melikoth Sep 18 '08 at 21:43
array_multisort() is the way I've always done it, though it can be a bit tricky to wrap your head around how it works at first. –  Garrett Albright Sep 18 '08 at 22:46
This is a very good example for figuring that out. –  Melikoth Sep 18 '08 at 23:24
So in this example, $mdarray might be a two-dimensional array, like an array of database records. In this example, 0 is the index of the 'date' column in each record (or row). So you construct the $dates array (basically the same array, but with only that column), and tell the array_multisort function to sort $mdarray based on that particular column's values. –  Dan Burton May 19 '10 at 18:26
For clarity, you might add to the beginning of this example $dates = array(); –  Dan Burton May 19 '10 at 18:27

Introducing: a very generalized solution for PHP 5.3+

I 'd like to add my own solution here, since it offers features that other answers do not.

Specifically, advantages of this solution include:

  1. It's reusable: you specify the sort column as a variable instead of hardcoding it.
  2. It's flexible: you can specify multiple sort columns (as many as you want) -- additional columns are used as tiebreakers between items that initially compare equal.
  3. It's reversible: you can specify that the sort should be reversed -- individually for each column.
  4. It's extensible: if the data set contains columns that cannot be compared in a "dumb" manner (e.g. date strings) you can also specify how to convert these items to a value that can be directly compared (e.g. a DateTime instance).
  5. It's associative if you want: this code takes care of sorting items, but you select the actual sort function (usort or uasort).
  6. Finally, it does not use array_multisort: while array_multisort is convenient, it depends on creating a projection of all your input data before sorting. This consumes time and memory and may be simply prohibitive if your data set is large.

The code

function make_comparer() {
    // Normalize criteria up front so that the comparer finds everything tidy
    $criteria = func_get_args();
    foreach ($criteria as $index => $criterion) {
        $criteria[$index] = is_array($criterion)
            ? array_pad($criterion, 3, null)
            : array($criterion, SORT_ASC, null);

    return function($first, $second) use (&$criteria) {
        foreach ($criteria as $criterion) {
            // How will we compare this round?
            list($column, $sortOrder, $projection) = $criterion;
            $sortOrder = $sortOrder === SORT_DESC ? -1 : 1;

            // If a projection was defined project the values now
            if ($projection) {
                $lhs = call_user_func($projection, $first[$column]);
                $rhs = call_user_func($projection, $second[$column]);
            else {
                $lhs = $first[$column];
                $rhs = $second[$column];

            // Do the actual comparison; do not return if equal
            if ($lhs < $rhs) {
                return -1 * $sortOrder;
            else if ($lhs > $rhs) {
                return 1 * $sortOrder;

        return 0; // tiebreakers exhausted, so $first == $second

How to use

Throughout this section I will provide links that sort this sample data set:

$data = array(
    array('zz', 'name' => 'Jack', 'number' => 22, 'birthday' => '12/03/1980'),
    array('xx', 'name' => 'Adam', 'number' => 16, 'birthday' => '01/12/1979'),
    array('aa', 'name' => 'Paul', 'number' => 16, 'birthday' => '03/11/1987'),
    array('cc', 'name' => 'Helen', 'number' => 44, 'birthday' => '24/06/1967'),

The basics

The function make_comparer accepts a variable number of arguments that define the desired sort and returns a function that you are supposed to use as the argument to usort or uasort.

The simplest use case is to pass in the key that you 'd like to use to compare data items. For example, to sort $data by the name item you would do

usort($data, make_comparer('name'));

See it in action.

The key can also be a number if the items are numerically indexed arrays. For the example in the question, this would be

usort($data, make_comparer(0)); // 0 = first numerically indexed column

See it in action.

Multiple sort columns

You can specify multiple sort columns by passing additional parameters to make_comparer. For example, to sort by "number" and then by the zero-indexed column:

usort($data, make_comparer('number', 0));

See it in action.

Advanced features

More advanced features are available if you specify a sort column as an array instead of a simple string. This array should be numerically indexed, and must contain these items:

0 => the column name to sort on (mandatory)
1 => either SORT_ASC or SORT_DESC (optional)
2 => a projection function (optional)

Let's see how we can use these features.

Reverse sort

To sort by name descending:

usort($data, make_comparer(['name', SORT_DESC]));

See it in action.

To sort by number descending and then by name descending:

usort($data, make_comparer(['number', SORT_DESC], ['name', SORT_DESC]));

See it in action.

Custom projections

In some scenarios you may need to sort by a column whose values do not lend well to sorting. The "birthday" column in the sample data set fits this description: it does not make sense to compare birthdays as strings (because e.g. "01/01/1980" comes before "10/10/1970"). In this case we want to specify how to project the actual data to a form that can be compared directly with the desired semantics.

Projections can be specified as any type of callable: as strings, arrays, or anonymous functions. A projection is assumed to accept one argument and return its projected form.

It should be noted that while projections are similar to the custom comparison functions used with usort and family, they are simpler (you only need to convert one value to another) and take advantage of all the functionality already baked into make_comparer.

Let's sort the example data set without a projection and see what happens:

usort($data, make_comparer('birthday'));

See it in action.

That was not the desired outcome. But we can use date_create as a projection:

usort($data, make_comparer(['birthday', SORT_ASC, 'date_create']));

See it in action.

This is the correct order that we wanted.

There are many more things that projections can achieve. For example, a quick way to get a case-insensitive sort is to use strtolower as a projection.

That said, I should also mention that it's better to not use projections if your data set is large: in that case it would be much faster to project all your data manually up front and then sort without using a projection, although doing so will trade increased memory usage for faster sort speed.

Finally, here is an example that uses all the features: it first sorts by number descending, then by birthday ascending:

usort($data, make_comparer(
    ['number', SORT_DESC],
    ['birthday', SORT_ASC, 'date_create']

See it in action.

share|improve this answer
Easily the most under-appreciated answer on this site. –  jmeas Jun 27 '13 at 1:01
I'm a little late to the party here, but just want to thank you for this. Very useful. –  robertgfthomas Sep 25 '13 at 12:43
This is probably the best answer I've seen on stackoverflow. Thank you for the beautiful piece of code and the wonderful documentation!!! –  maddob Oct 4 '13 at 12:47
@Jon - Thanks for all of your help. I tried to implement this on my server and I get this:PHP Parse error: syntax error, unexpected '[', expecting ')' -- I tried different variation, I'm just a bit lost on how this really works. I'm on v5.3.28 - ideone.com runs php 5.4 - is that the issue? –  Ecropolis Jun 5 at 20:34
@YahyaE: Sorting arrays of objects? Replace $first[$column] with $first->$column, and same for $second. Four replacements in total. –  Jon Oct 10 at 0:02

With usort. Here's a generic solution, that you can use for different columns:

class TableSorter {
  protected $column;
  function __construct($column) {
    $this->column = $column;
  function sort($table) {
    usort($table, array($this, 'compare'));
    return $table;
  function compare($a, $b) {
    if ($a[$this->column] == $b[$this->column]) {
      return 0;
    return ($a[$this->column] < $b[$this->column]) ? -1 : 1;

To sort by first column:

$sorter = new TableSorter(0); // sort by first column
$mdarray = $sorter->sort($mdarray);
share|improve this answer
I get Parse error: parse error, unexpected T_STRING, expecting T_OLD_FUNCTION or T_FUNCTION or T_VAR or '}' on the second line of that class. –  Melikoth Sep 18 '08 at 21:35
this code requires php5 –  Devon Sep 18 '08 at 21:50
Replace "protrected" with "var" and "__construct" with "TableSorter", and it will work in PHP4. Notice however, that PHP4 is discontinued. –  troelskn Sep 18 '08 at 22:23
I set PHP to v5, didn't know it was running v4 by default. Having looked at it for a while I think I understand how to modify it for different types of sorts as well –  Melikoth Sep 18 '08 at 23:19
oh wow this works great. Thank you a million! –  Kayvar Apr 30 '13 at 0:36

I know it's 2 years since this question was asked and answered, but here's another function that sorts a two-dimensional array. It accepts a variable number of arguments, allowing you to pass in more than one key (ie column name) to sort by. PHP 5.3 required.

function sort_multi_array ($array, $key)
  $keys = array();
    $keys[$i-1] = func_get_arg($i);

  // create a custom search function to pass to usort
  $func = function ($a, $b) use ($keys) {
      if ($a[$keys[$i]] != $b[$keys[$i]]) {
        return ($a[$keys[$i]] < $b[$keys[$i]]) ? -1 : 1;
    return 0;

  usort($array, $func);

  return $array;

Try it here: http://www.exorithm.com/algorithm/view/sort_multi_array

share|improve this answer
Could the first 3 lines of the function be replaced with $keys = func_get_args(); array_unshift($keys);? –  user212218 Mar 13 '12 at 18:44
yes, I believe so –  Mike C Mar 13 '12 at 20:52

The "Usort" function is your answer.

share|improve this answer

Multiple row sorting using a closure

Here's another approach using uasort() and an anonymous callback function (closure). I've used that function regularly. PHP 5.3 required – no more dependencies!

 * Sorting array of associative arrays - multiple row sorting using a closure.
 * See also: http://the-art-of-web.com/php/sortarray/
 * @param array $data input-array
 * @param string|array $fields array-keys
 * @license Public Domain
 * @return array
function sortArray( $data, $field ) {
    $field = (array) $field;
    uasort( $data, function($a, $b) use($field) {
        $retval = 0;
        foreach( $field as $fieldname ) {
            if( $retval == 0 ) $retval = strnatcmp( $a[$fieldname], $b[$fieldname] );
        return $retval;
    } );
    return $data;

/* example */
$data = array(
    array( "firstname" => "Mary", "lastname" => "Johnson", "age" => 25 ),
    array( "firstname" => "Amanda", "lastname" => "Miller", "age" => 18 ),
    array( "firstname" => "James", "lastname" => "Brown", "age" => 31 ),
    array( "firstname" => "Patricia", "lastname" => "Williams", "age" => 7 ),
    array( "firstname" => "Michael", "lastname" => "Davis", "age" => 43 ),
    array( "firstname" => "Sarah", "lastname" => "Miller", "age" => 24 ),
    array( "firstname" => "Patrick", "lastname" => "Miller", "age" => 27 )

$data = sortArray( $data, 'age' );
$data = sortArray( $data, array( 'lastname', 'firstname' ) );
share|improve this answer

Here is a php4/php5 class that will sort one or more fields:

// a sorter class
//  php4 and php5 compatible
class Sorter {

  var $sort_fields;
  var $backwards = false;
  var $numeric = false;

  function sort() {
    $args = func_get_args();
    $array = $args[0];
    if (!$array) return array();
    $this->sort_fields = array_slice($args, 1);
    if (!$this->sort_fields) return $array();

    if ($this->numeric) {
      usort($array, array($this, 'numericCompare'));
    } else {
      usort($array, array($this, 'stringCompare'));
    return $array;

  function numericCompare($a, $b) {
    foreach($this->sort_fields as $sort_field) {
      if ($a[$sort_field] == $b[$sort_field]) {
      return ($a[$sort_field] < $b[$sort_field]) ? ($this->backwards ? 1 : -1) : ($this->backwards ? -1 : 1);
    return 0;

  function stringCompare($a, $b) {
    foreach($this->sort_fields as $sort_field) {
      $cmp_result = strcasecmp($a[$sort_field], $b[$sort_field]);
      if ($cmp_result == 0) continue;

      return ($this->backwards ? -$cmp_result : $cmp_result);
    return 0;

// usage examples

// some starting data
$start_data = array(
  array('first_name' => 'John', 'last_name' => 'Smith', 'age' => 10),
  array('first_name' => 'Joe', 'last_name' => 'Smith', 'age' => 11),
  array('first_name' => 'Jake', 'last_name' => 'Xample', 'age' => 9),

// sort by last_name, then first_name
$sorter = new Sorter();
print_r($sorter->sort($start_data, 'last_name', 'first_name'));

// sort by first_name, then last_name
$sorter = new Sorter();
print_r($sorter->sort($start_data, 'first_name', 'last_name'));

// sort by last_name, then first_name (backwards)
$sorter = new Sorter();
$sorter->backwards = true;

// sort numerically by age
$sorter = new Sorter();
$sorter->numeric = true;
print_r($sorter->sort($start_data, 'age'));
share|improve this answer
Does this only work with associative arrays? –  Melikoth Sep 18 '08 at 23:23
yes - associative arrays only. Now that I look at it, it is not the right solution for this problem. –  Devon Sep 22 '08 at 20:54
function cmp($a, $b)
$p1 = $a['price'];
$p2 = $b['price'];
return (float)$p1 > (float)$p2;
uasort($my_array, "cmp");
share|improve this answer

Before I could get the TableSorter class to run I had came up with a function based on what Shinhan had provided.

function sort2d_bycolumn($array, $column, $method, $has_header)
  if ($has_header)  $header = array_shift($array);
  foreach ($array as $key => $row) {
    $narray[$key]  = $row[$column]; 
  array_multisort($narray, $method, $array);
  if ($has_header) array_unshift($array, $header);
  return $array;
  • $array is the MD Array you want to sort.
  • $column is the column you wish to sort by.
  • $method is how you want the sort performed, such as SORT_DESC
  • $has_header is set to true if the first row contains header values that you don't want sorted.
share|improve this answer

Here is my implementation. I had a category object which incorporated category entries. I wanted to sort those entries by a sub-array value. Here's how I went about it.

Where $in_cat_team_arr is the unsorted array

//sort multidimensional array by $order_in_category
if (count ($in_cat_team_arr) > 0) {
    foreach ($in_cat_team_arr as $key => $row) {
        $order_in_category[$key]  = $row[0];//[0] is $order_in_category
    array_multisort($order_in_category, SORT_ASC, $in_cat_team_arr);

foreach ($in_cat_team_arr as $team_mem) {
    //loop through the sorted array here

This works nicely for me.

I do have a question though. Is there any way to use the key name rather than index (e.g. $row['my_key_name'] instead of $row[0])? I tried this and it got scrambled.

share|improve this answer

I prefer to use array_multisort. See the documentation here.

share|improve this answer

I tried several popular array_multisort() and usort() answers and none of them worked for me. The data just gets jumbled and the code is unreadable. Here's a quick a dirty solution. WARNING: Only use this if you're sure a rogue delimiter won't come back to haunt you later!

Let's say each row in your multi array looks like: name, stuff1, stuff2:

// Sort by name, pull the other stuff along for the ride
foreach ($names_stuff as $name_stuff) {
    // To sort by stuff1, that would be first in the contatenation
    $sorted_names[] = $name_stuff[0] .','. name_stuff[1] .','. $name_stuff[2];
sort($sorted_names, SORT_STRING);

Need your stuff back in alphabetical order?

foreach ($sorted_names as $sorted_name) {
    $name_stuff = explode(',',$sorted_name);
    // use your $name_stuff[0] 
    // use your $name_stuff[1] 
    // ... 

Yeah, it's dirty. But super easy, won't make your head explode.

share|improve this answer

protected by Robert Harvey Oct 22 '12 at 1:49


Would you like to answer one of these unanswered questions instead?
