I have an unsorted 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 this:
[0] => 11-01-2012
[1] => 01-01-2013
[2] => 09-02-2013
[3] => 01-01-2014
[4] => 01-01-2015
I tried asort
, but that did not work. How can I sort it?
If the date were in "MySQL" format (Y-m-d
or Y-m-d H:i:s
), then you could sort your array with 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 in any way (something you should avoid; you should format the date only when you need to output/display it, if necessary), then you have to use a custom sorting function, such as usort()
, that will convert the dates into a sortable format before comparison.
The simplest way to convert a date into a sortable format is to convert it into a Unix timestamp using the 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);
You check the result in this demo.
However, there could be pitfalls, because in different countries the same date format could indicate a different date, which is exactly the case with your example dates, 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 alternative answer by Damien Jiang.