I'm working in php and I have a list of dates in string format. I'd like to get the newest one, and have the function return it.. I can't seem to get this to work.. Maybe someone can help me out..
<?php
$list_of_dates = array("04/17/1999 05:15 AM - CST", "04/17/2000 05:18 AM - CST", "04/17/2000 05:19 AM - CST");
function getLatestDate($in){
$ret = "";
foreach($in as &$date){
$cnt = strtotime($date);
if(strtotime($ret) > $cnt){
$ret = $date;
}
}
return $ret;
}
?>
Your condition seems to be reversed:
if(strtotime($ret) > $cnt){
$ret = $date;
}
Should be:
if ($ret === '' || strtotime($ret) < $cnt){
$ret = $date;
}
You will want to overwrite $ret
if its value is lower (older) than $cnt
. In the first iteration $ret
will be the empty string, so you will always want to overwrite that; of course, strtotime('')
will probably always be lower than anything else, but it's good form to make the distinction.