28

I am new to php, I have php date array

[0] => 11-01-2012
[1] => 01-01-2014
[2] => 01-01-2015
[3] => 09-02-2013
[4] => 01-01-2013

I want to sort it like :

[0] => 11-01-2012
[1] => 01-01-2013
[2] => 09-02-2013
[3] => 01-01-2014
[4] => 01-01-2015

I use asort but not working.

Your Common Sense
  • 156,878
  • 40
  • 214
  • 345
Mojilo
  • 335
  • 1
  • 3
  • 7
  • 1
    It looks like you are trying to sort strings instead of dates. You should convert your data to real dates (DateTime objects or timestamps); then you can manipulate them very easily. – jeroen Nov 07 '16 at 10:24
  • http://stackoverflow.com/questions/6401714/php-order-array-by-date – Goku Nov 07 '16 at 10:25
  • 2
    Possible duplicate of [Sorting arrays by date](http://stackoverflow.com/questions/9203079/sorting-arrays-by-date) – Nikhil Vaghela Nov 07 '16 at 10:26
  • Despite my change to the title, the [mcve] isn't crystal clear about whether the strings are `d-m-Y` or `m-d-Y`. – mickmackusa Jun 21 '22 at 06:11

8 Answers8

64

If the date is in "Mysql" format (Y-m-d or Y-m-d H:i:s), then you can sort your array right away, no special action needed:

$arr = ["2019-11-11", "2019-10-10","2019-11-11", "2019-09-08","2019-05-11"];
sort($arr);

If the date is localized or formatted anyhow (that you should avoid, formatting the date only before output) you have to use a custom sorting function, such as usort(), that will convert the dates into sortable format before comparison.

The simplest way to convert a date into sortable format is to convert it into uninx timestamp using strtotime() function:

$arr = ['11/01/2012', '03/16/2022', '12/26/2021', '01/01/2014', '09/02/2013'];
usort($arr, function ($a, $b) {
    return strtotime($a) - strtotime($b);
});
print_r($arr);

Check result in demo

However, there could be pitfalls, because in different countries the same date format could mean a different date. Which is exactly the case with your example format, for which the above function will return wrong results if dates are ['03-16-2022', '12-26-2021', '06-06-2022']. Therefore it's better to define the date format explicitly, as explained in this answer

Your Common Sense
  • 156,878
  • 40
  • 214
  • 345
d.coder
  • 1,988
  • 16
  • 23
3

The example dates data provided aren't clear what format they are. To be sure, you should use DateTime::createFromFormat and then specify the format explicitly:

$dates = ['11-01-2012', '03-16-2022', '12-26-2021', '01-01-2014', '01-01-2015', '09-02-2013', '01-01-2013'];

function sort_date($a, $b) {
    return \DateTime::createFromFormat('m-d-Y', $a) <=> \DateTime::createFromFormat('m-d-Y', $b);
}

usort($dates, "sort_date");
Your Common Sense
  • 156,878
  • 40
  • 214
  • 345
DAMIEN JIANG
  • 573
  • 4
  • 16
  • Related: https://stackoverflow.com/q/63482679/2943403 , https://stackoverflow.com/q/39769867/2943403 , https://stackoverflow.com/q/59151489/2943403 , https://stackoverflow.com/q/23130621/2943403 – mickmackusa Jun 21 '22 at 05:59
1

Try below code:

<?php 

$array = array('11-01-2012','01-01-2011','09-02-2013','01-01-2014','01-01-2015');

function cmp($a, $b)
{
    $a = date('Y-m-d', strtotime($a));
    $b = date('Y-m-d', strtotime($b));

    if ($a == $b) {
        return 0;
    }
    return ($a < $b) ? -1 : 1;
}
usort($array, "cmp");

foreach ($array as $key => $value) {
    echo "[$key]=> $value <br>";
}
?>
Soni Vimalkumar
  • 1,449
  • 15
  • 26
  • _Try this_ (code-only) answers are low value on Stackoverflow because they do very little to educate/empower the OP and future researchers. Please add an explanation of how your solution works and why it is a good idea. – mickmackusa Sep 19 '18 at 12:01
0

out of the box use time function to generate ts and sort

<?php
  $out = array();
  // $your_array is the example obove
  foreach($your_array as $time) {
  $out[strtotime($time)] = $time;
  }
  // now $out has ts-keys and you can handle it

  ...
 ?>

ksort

donald123
  • 5,638
  • 3
  • 26
  • 23
0

Try this,

<?php 
$array = [ '11-01-2012', '01-01-2014', '01-01-2015', '09-02-2013', '01-01-2013' ];
function sortFunction( $a, $b ) {
    return strtotime($a) - strtotime($b);
}
usort($array, "sortFunction");
var_dump( $array );
?>

Will sort the dates into the order you want.

Blinkydamo
  • 1,582
  • 9
  • 20
  • 1
    Try this (code-only) answers are low value on Stackoverflow because they do very little to educate/empower the OP and future researchers. Please add an explanation of how your solution works and why it is a good idea. – mickmackusa Sep 19 '18 at 12:03
0

I solved this problem by applying this line.

sort($imdarrayGG['newDate']);

Output before adding the value

[Mon Jul  6 10:33:23 2020] Array
(
    [coursedate] => 2020-07-17
    [newDate] => Array
        (
            [0] => 2020-07-30
            [1] => 2020-07-07
            [2] => 2020-07-08
            [3] => 2020-07-17
        )

)

After I put the line, the output will become like this.

[Mon Jul  6 10:35:42 2020] Array
(
    [coursedate] => 2020-07-17
    [newDate] => Array
        (
            [0] => 2020-07-07
            [1] => 2020-07-08
            [2] => 2020-07-17
            [3] => 2020-07-30
        )

)

The date already sorted which is the latest date will be at the up.

This is where we have object and then we want to sort all of them

Example:-

[status_custom] => Array
    (
        [0] => stdClass Object
            (
                [type] => LDL - B2
                [date] => 23/10/2014
            )

        [1] => stdClass Object
            (
                [type] => LDL - D
                [date] => 18/04/2015
            )
   )

First we have to convert. Refer to this link to convert And then we sort them. Refer to this link to sort object

Here we go:-

    //At here we want to sort according to latest date. But this one involve with the object also.
    usort($array_custom_object, function ($a, $b) {
        $date1 = $a->date;
        $date2 = $b->date;

        //Since the income date is formatted like this d/m/Y , we have to change it
        $date1 = date_format(date_create_from_format('d/m/Y', $date1), 'Y-m-d');
        $date2 = date_format(date_create_from_format('d/m/Y', $date2), 'Y-m-d');

        if ($date1 > $date2) {
            return -1;
        }
        if ($date1 == $date2) {
            return 0;
        }
        if ($date1 < $date2) {
            return 1;
        }
    });
    $dataFinal->status_custom = $array_custom_object; //Result
Ticherhaz FreePalestine
  • 2,738
  • 4
  • 20
  • 46
-1

use DateTime for sorting date :

$a = array(
    new DateTime('2016-01-02'),
    new DateTime('2016-05-01'),
    new DateTime('2015-01-01'),
    new DateTime('2016-01-01')
);
asort($a);
var_dump($a);

The output would be :

array(4) {
  [2]=>
  object(DateTime)#3 (3) {
    ["date"]=>
    string(26) "2015-01-01 00:00:00.000000"
    ["timezone_type"]=>
    int(3)
    ["timezone"]=>
    string(10) "US/Pacific"
  }
  [3]=>
  object(DateTime)#4 (3) {
    ["date"]=>
    string(26) "2016-01-01 00:00:00.000000"
    ["timezone_type"]=>
    int(3)
    ["timezone"]=>
    string(10) "US/Pacific"
  }
  [0]=>
  object(DateTime)#1 (3) {
    ["date"]=>
    string(26) "2016-01-02 00:00:00.000000"
    ["timezone_type"]=>
    int(3)
    ["timezone"]=>
    string(10) "US/Pacific"
  }
  [1]=>
  object(DateTime)#2 (3) {
    ["date"]=>
    string(26) "2016-05-01 00:00:00.000000"
    ["timezone_type"]=>
    int(3)
    ["timezone"]=>
    string(10) "US/Pacific"
  }
}
MaximeK
  • 2,039
  • 1
  • 10
  • 16
  • 1
    Your answer here is close if you have a list of DateTime or Carbon date objects. However I believe you have negative down votes because you suggested using asort() instead of sort(), If users use asort() then numerical index references will not reflect the actual sorted list that is dumped. – Marc Jan 11 '19 at 12:05
-1

You definitely can sort array to timestamps with the given code below, but I would like to drag your attention to the format of time I have used to store.. There are different benefits of storing time in such format. Read more about this here https://stackoverflow.com/a/59912185/7997043

function compareByTimeStamp($a, $b ) {
    return strtotime($b) - strtotime($a);
}
$arr = array("2020-02-11 00:00:00", "2020-02-13 00:00:00", "2020-02-08 00:00:00"); 
usort($arr, "compareByTimeStamp"); 
echo json_encode($arr);
NAVNEET CHANDAN
  • 268
  • 3
  • 7