PHP变量字符串中的IF / ELSE语句

时间:2014-11-07 19:04:24

标签: php html if-statement

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

示例:

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

显然这个例子不起作用,但是你看到我正在尝试做什么。我知道我可以继续if语句中的变量,如:

$htmlOutput .= '';

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

3 个答案:

答案 0 :(得分:5)

您可以使用ternary operator这样的

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

答案 1 :(得分:1)

使用三元运算符而不是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';

答案 2 :(得分:1)

这应该适合你:

<?php


    $time = "night";

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

    echo $htmlOutput;


?>
相关问题