我正在尝试使用三元运算符来缩短代码。
这是我的原始代码:
if ($type = "recent") {
$OrderType = "sid DESC";
} elseif ($type = "pop") {
$OrderType = "counter DESC";
} else {
$OrderType = "RAND()";
}
如何在代码中使用三元运算符而不是if
s / else
?
$OrderType = ($type = "recent") ? "sid DESC" : "counter DESC" ;
这是我尝试的代码,但不知道如何添加“elseif
部分”。
答案 0 :(得分:14)
这称为三元运算符; - )
你可以使用其中两个:
$OrderType = ($type == 'recent' ? 'sid DESC' : ($type == 'pop' ? 'counter DESC' : 'RAND()'))
这可以理解为:
$type
是'recent'
'sid DESC'
$type
是'pop'
'counter DESC'
'RAND()'
几个笔记:
==
或===
;而不是=
()
,以便于阅读
并且,作为关于三元运算符的参考,引用Operators section of the PHP manual:
第三组是三元组 运营商:
?:
。
应该使用它 在两个表达式之间进行选择 取决于第三个,而不是 选择两个句子或路径 执行。
周围三元 用括号括起来的表达式是非常的 好主意。
答案 1 :(得分:3)
我建议改用案例陈述。当你想要添加额外的选项时,它会使它更具可读性,但更易于维护
switch ($type)
{
case "recent":
$OrderType = "sid DESC";
break;
case "pop":
$OrderType = "counter DESC";
break;
default:
$OrderType = "RAND()";
}