比较变量并设置第一个具有值的变量


Compare variables and set the first that has value

我有一个事件列表循环,我从事件的日期和今天的日期中创建了变量。有一个必填$maindate,但同一事件的其他日期$otherdates,晚于主要日期。我想设置在单独变量中设置的最新日期,并将其与今天的日期进行比较,以使 if ( $comparedate>= $today ) 仅控制未来事件的列表。

这是我的变量:

    $maindate = DateTime::createFromFormat('Ymd', get_field('date'));
    $otherdates1 = DateTime::createFromFormat('Ymd', get_field('other_dates'));
    $otherdates2 = DateTime::createFromFormat('Ymd', get_field('other_dates_2'));
    $otherdates3 = DateTime::createFromFormat('Ymd', get_field('other_dates_3'));
    $today = DateTime::createFromFormat('Ymd', date('Ymd'));
/* I need to set up the first available variable here */    
$comparedate = $otherdates3 || $otherdates2 || $otherdates1 || $maindate;
if ( $comparedate >= $today ) : 
/* list the future events */

如何进行此比较?

$lastestDate = null;
$datesSet = [$maindate, $otherdates1, $otherdates2, $otherdates3];
foreach($datesSet as $date) {
     if($lastestDate == null || $lastestDate->getTimeStamp() < $date->getTimeStamp())
          $lastestDate = $date;
}
$comparedate = $lastestDate;

正如 Ianis 所指出的,我必须通过 php max 运算符比较变量,if 语句会像这样获得最新的日期。

变量为:

$comparedate = max( $maindate, $otherdates1, $otherdates2, $otherdates3 );