【问题标题】:How to use ternary operators if-elseif-else in php? [duplicate]如何在php中使用三元运算符if-elseif-else? [复制]
【发布时间】:2019-05-09 03:25:25
【问题描述】:

我想对 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 为空白时,它会返回凌晨 1 点。我想当 $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)));
    }
}

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

【问题讨论】:

  • 三元...但是当你有一个 if else 以一种更清晰、更容易阅读的方式做同样的事情时,为什么你想要一个凌乱的三元呢?
  • @Andreas 感谢您的回复。我正在学习代码,所以我想学习如何在一行中使用这些东西。
  • isset((openMon == "") 这在您的if 循环中有效吗? (缺少$)。也不要“询问”是否设置了openMon == ""。询问是否设置了$openMon。或者如果$openMon == ""。你在做这两件事
  • 单行代码是一种凌乱的编码方式,当您需要调试或更改某些内容时,您会后悔的。如果超过两个条件,我强烈建议您不要使用三元。我个人从不使用它,除非......好吧,我不知道如何找到它......
  • @kerbholz 谢谢你的回复。我的 if-else 工作正常,但我想在 turnary 运算符中使用。如果-elseif-else。

标签: php ternary-operator


【解决方案1】:

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

你的代码会是这样的:

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

你可以测试这段代码 sn -p here.

【讨论】:

  • 感谢您的回复。你是一个伟大的编码员。我想学习,你教我。谢谢。
  • 祝你编码愉快!最好的问候。)
猜你喜欢
  • 2021-01-03
  • 1970-01-01
  • 1970-01-01
  • 2021-03-31
  • 2020-05-17
  • 2011-02-11
  • 2015-06-05
  • 1970-01-01
  • 2019-11-30
相关资源
最近更新 更多