【问题标题】:IF/ELSE statement inside PHP variable stringPHP 变量字符串中的 IF/ELSE 语句
【发布时间】:2014-11-07 19:04:23
【问题描述】:

在变量字符串中使用 IF/ELSE 语句的正确方法是什么?

例子:

$htmlOutput = 'The current color of the sky is ' . 
if ($time==="day") { . 'blue.' . } 
else if ($time==="night") { . 'black' . };

显然,该示例不起作用,但您可以看到我正在尝试做的事情。我知道我可以继续 if 语句中的变量,例如:

$htmlOutput .= '';

但我很好奇是否有如上所述的方法。

【问题讨论】:

  • 是的,ternary operator
  • 避免在三元运算中做任何比单个if x then y else z 更复杂的事情。它们可以嵌套,但很快就会变得非常不可读。 (if x then (if a then b else c) else z)

标签: php html if-statement


【解决方案1】:

你可以像这样使用ternary operator

$htmlOutput = 'The current color of the sky is ' . ($time == 'day' ? 'blue' : 'black');

【讨论】:

  • 太完美了,谢谢!感谢所有这么快回答的人。
【解决方案2】:

这应该适合你:

<?php


    $time = "night";

    $htmlOutput = 'The current color of the sky is ' . ($time === 'day' ? 'blue' : 'black');

    echo $htmlOutput;


?>

【讨论】:

    【解决方案3】:

    使用三元运算符而不是 if else

     $htmlOutput = 'The current color of the sky is ' . ($time==="day") ?'blue':($time==="night")?'black':'';
    

    或者更简单的是

       $htmlOutput = 'The current color of the sky is ' . ($time==="day") ?'blue':'black';
    

    【讨论】:

    • 第一个看起来很时髦。它要么有一个额外的?,要么缺少一个:
    • 用于else if,多重操作语句
    • 是的,但它不是有效的语法。第二个看起来不错。
    猜你喜欢
    • 2018-03-09
    • 1970-01-01
    • 2018-01-09
    • 1970-01-01
    • 1970-01-01
    • 2013-02-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多