我正在尝试使用三元运算符来缩短代码.
这是我的原始代码:
if ($type = "recent") { $OrderType = "sid DESC"; } elseif ($type = "pop") { $OrderType = "counter DESC"; } else { $OrderType = "RAND()"; }
如何在代码中使用三元运算符而不是ifs / elses?
$OrderType = ($type = "recent") ? "sid DESC" : "counter DESC" ;
这被称为三元运算符;-)
原文链接:https://www.f2er.com/php/133192.html你可以使用其中两个:
$OrderType = ($type == 'recent' ? 'sid DESC' : ($type == 'pop' ? 'counter DESC' : 'RAND()'))
这可以理解为:
>如果$type是’recent’
>然后使用’sid DESC’
>否则
>如果$type是’pop’
>然后使用’柜台DESC’
>否则使用’RAND()’
几个笔记:
>你必须使用==或===;而不是=
>前两个是comparison operators
>最后一个是assignment operator
>最好使用(),使事情更容易阅读
>你不应该使用太多这样的三元运算符:我认为它使代码有点难以理解
并且,作为关于三元运算符的参考,引用Operators section of the PHP manual:
The third group is the ternary
operator:?:
. It should be used to select between two expressions depending on a third one,rather than to select two sentences or paths of execution. Surrounding ternary expressions with parentheses is a very good idea.