如何在PHP中使用三元运算符if-elseif-else?

时间:2018-12-07 11:03:03

标签: php ternary-operator

我想对if-elseif-else使用三元运算符。但这对我不起作用。

请检查以下代码:

$openMon = "00:01";  // The below Line Returns Time
$openMon = "00:00";  // The below Line Returns Close

<td><?=(($openMon == '00:00')?'Close':date("g:i a", strtotime($openMon)));?></td>

上面的行完美工作,因为它返回True或false。

但是,当$ openMon为空时,它将返回1am。我想当$ openMon为空白时返回“-”

我希望在一行中显示三件事:

$openMon = "";        // This is I want in ternary operator with above two conditions

if($openMon == "" ){
    $openMon ="-";
}

我尝试过:

<td><?=isset((openMon == "")?'-':(($openMon == '00:00')?'Close':date("g:i a", strtotime($openMon)));?></td>

这对我不起作用。

基本上我想使用三元运算符:

if($openMon == ''){
    $openMon = "-";
}else{
    if($openMon == '00:00'){
        $openMon = "Close";
    }else{
        $openMon = date("g:i a", strtotime($openMon)));
    }
}

任何想法或建议都会有所帮助。

1 个答案:

答案 0 :(得分:-1)

您可以使用嵌套三元运算符。 同样的问题是here

您的代码将如下所示:

$openMon = !$openMon ? "-" : ($openMon == '00:00' ? "Close" : date("g:i a", strtotime($openMon)))

您可以测试此代码段here