[英]IF/ELSE statement inside PHP variable string
在变量字符串中使用IF / ELSE语句的正确方法是什么?
例:
$htmlOutput = 'The current color of the sky is ' .
if ($time==="day") { . 'blue.' . }
else if ($time==="night") { . 'black' . };
显然,该示例不起作用,但是您会看到我正在尝试做的事情。 我知道我可以继续在if语句中添加变量,例如:
$htmlOutput .= '';
但我很好奇是否有如上所述的方法。
您可以像这样使用ternary operator
$htmlOutput = 'The current color of the sky is ' . ($time == 'day' ? 'blue' : 'black');
使用三元运算符代替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';
这应该为您工作:
<?php
$time = "night";
$htmlOutput = 'The current color of the sky is ' . ($time === 'day' ? 'blue' : 'black');
echo $htmlOutput;
?>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.