How to sort an array of dates in ascending order with PHP

1 Answer

0 votes
function compareByTimeStamp($time1, $time2) { 
    if (strtotime($time1) < strtotime($time2)) 
        return 1; 
    else if (strtotime($time1) > strtotime($time2))  
        return -1; 
    else
        return 0; 
} 
  
$arr = array("13-02-2007",
             "19-04-2011",               
             "18-04-2011",
             "01-03-1966",
             "17-05-2019",
             "17-12-1980",
             "21-06-2017",
             "17-05-2020"); 
 
usort($arr, "compareByTimeStamp"); 
  
print_r($arr); 



/*
run:

Array
(
    [0] => 17-05-2020
    [1] => 17-05-2019
    [2] => 21-06-2017
    [3] => 19-04-2011
    [4] => 18-04-2011
    [5] => 13-02-2007
    [6] => 17-12-1980
    [7] => 01-03-1966
)

*/

 



answered May 19, 2020 by avibootz
edited May 19, 2020 by avibootz

Related questions

2 answers 246 views
1 answer 148 views
1 answer 111 views
2 answers 154 views
1 answer 173 views
1 answer 133 views
...