How to sort date array in php?
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");
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