2

I am trying to order this array chronologically:

$ta = array (
    0 => '20/05/2012',
    1 => '08/01/2011',
    2 => '23/10/2010',
    3 => '27/07/2013',
    4 => '28/01/2011',
    5 => '21/10/2010',
    5 => '18/07/2013',
);


function comp2($a, $b) {
    if ($a == $b)
        return 0;

    return ($a < $b) ? 1 : -1;
};

usort($ta,'comp2');

This returns:

  Array
(
  [0] => 28/01/2011
  [1] => 27/07/2013
  [2] => 23/10/2010
  [3] => 20/05/2012
  [4] => 18/07/2013
  [5] => 08/01/2011
)

I have also converted dates with strtotime after changing to mm/dd/yyyy to no avail.

succeed
  • 834
  • 1
  • 11
  • 28
  • 4
    That input most certainly will not return that output. Your date formats are different... – deceze Oct 02 '15 at 10:42
  • 1
    Firstly, avoid doing any kind of date processing using strings, especially strings in a non-sortable date format. The first thing you should do when getting a date string as input into your program is convert it into a DateTime object. They will then be easy to sort, or do any other date processing with. You can convert it back to a formatted string if necessary when you output it back to the user, but while it's inside your program, always use the DateTime objects. – Simba Oct 02 '15 at 10:49
  • @deceze you're right, I was also testing with american format and pasting the return from the wrong screen. Edited to show actual return now. – succeed Oct 02 '15 at 11:12

2 Answers2

3

You can simply use usort like as

usort($ta,function($a,$b){
    return strtotime(str_replace('/', '-', $a)) - strtotime(str_replace('/', '-', $b));
});

Brief Explanation :

Here the date structure that you have is American Date Format which is m/d/Y. So that needs to be replace into European Date Format first i.e. d-m-y . You can check this answer for PHP date conversion to strtotime.

Demo

Community
  • 1
  • 1
Narendrasingh Sisodia
  • 21,247
  • 6
  • 47
  • 54
0

Just sorting them as strings will not work, as it will order them alphabetically. The first of january 1988 will then come before the last of december 2015 since it starts with the first characters - the days.

So you will have to convert the strings to dates. The problem here is that strtotime() doesnt accept the dd/mm/YYYY format. Using this workaround you get the following code:

function comp2($a, $b) {
    $x = toDate($a);
    $y = toDate($b);
    if ($x == $y) return 0;
    return ($x < $y) ? 1 : -1;
}

function toDate($d) {
    return strtotime(str_replace('/', '-', $d));
}

If you have a lot of dates to sort, this is not very efficient, though. The same date will be compared to multiple dates, and therefore converted multiple times. That is a waste of resources. So if performance is an issue, loop through the array an convert all dates and then sort it just using sort(). After that you can convert back to whatever format you want using date().

Community
  • 1
  • 1
Anders
  • 8,307
  • 9
  • 56
  • 88