How to sort a date array in PHP

Use the ISO (yyyy-mm-dd) format rather than the “english” format, and then just use the ksort function to get them in the right order.

There’s no need to remove the hyphens, ksort will do an alphanumeric comparison on the string keys, and the yyyy-mm-dd format works perfectly well as the lexical order is the same as the actual date order.

EDIT I see you’ve now corrected your question to show that you’ve actually got an array of arrays, and that the sort key is in the sub-arrays. In this case, you should use uksort as recommended elsewhere, but I would recommend that you go with your own edit and sort based on the DB formatted date, rather than by parsing the human readable format:

function cmp($a, $b)
{
    global $array;
    return strcmp($array[$a]['db'], $array[$b]['db']);
}

uksort($array, 'cmp');

Leave a Comment