I have the following array
$dates = array(
'2015-02-13',
'2015-04-21',
'2015-08-18',
'2015-11-26',
'2015-09-15',
'2015-01-07',
'2015-02-11',
'2015-07-14',
'2015-03-02',
);
I would like to sort this array from longest ago to most recent date.
foreach ($dates as $date) {
$date = new DateTime($date);
// The logic I need
}
The dates you have are in shortened ISO8601 format, i.e. YYYY-MM-DD
.
These have the nice feature that the lexical sort order is the same as date order. So, just sort the array using the default sort function. It'll work.
When handling date strings inside code it's always a good idea to have ISO8601 be the canonical internal date format. Convert user-supplied to that as soon as possible, and if the user requires output to be in their own locale then defer that to as late as possible. Of course, using a "proper" date object is better still!