PHP order array by date? [duplicate] PHP order array by date? [duplicate] arrays arrays

PHP order array by date? [duplicate]


You don't need to convert your dates to timestamps before the sorting, but it's a good idea though because it will take more time to sort without this step.

$data = array(    array(        "title" => "Another title",        "date"  => "Fri, 17 Jun 2011 08:55:57 +0200"    ),    array(        "title" => "My title",        "date"  => "Mon, 16 Jun 2010 06:55:57 +0200"    ));function sortFunction( $a, $b ) {    return strtotime($a["date"]) - strtotime($b["date"]);}usort($data, "sortFunction");var_dump($data);

Update

In newer PHP versions you can use arrow functions too. Here you can find a more concise version of the above:

usort($data, fn ($a, $b) => strtotime($a["date"]) - strtotime($b["date"]));


Use usort:

usort($array, function($a1, $a2) {   $v1 = strtotime($a1['date']);   $v2 = strtotime($a2['date']);   return $v1 - $v2; // $v2 - $v1 to reverse direction});


I recommend using DateTime objects instead of strings, because you cannot easily compare strings, which is required for sorting. You also get additional advantages for working with dates.

Once you have the DateTime objects, sorting is quite easy:

usort($array, function($a, $b) {  return ($a['date'] < $b['date']) ? -1 : 1;});