To sort dates given in the form of an array in PHP, the code is as follows −
Example
<?php function compare_dates($time_1, $time_2) { if (strtotime($time_1) > strtotime($time_2)) return -1; else if (strtotime($time_1) < strtotime($time_2)) return 1; else return 0; } $my_arr = array("2020-09-23", "2090-12-06", "2002-09-11", "2009-30-11"); usort($my_arr, "compare_dates"); print_r("The dates in sorted order is "); print_r($my_arr); ?>
Output
The dates in sorted order is Array ( [0] => 2090-12-06 [1] => 2020-09-23 [2] => 2002-09-11 [3] => 2009-30-11 )
A function named ‘compare_dates’ takes two time formats as parameters. If the first time format is greater than the second one, it returns -1. Otherwise, if the first time format is lesser than the second time, it returns 1 and if both the conditions are not true, the function returns 0. An array is defined that contains various dates. The ‘usort’ function is applied on this array the sorted dates are displayed on the console.