加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

如何在PHP中使用三元运算符而不是if-else

发布时间:2020-12-13 22:39:24 所属栏目:PHP教程 来源:网络整理
导读:我正在尝试使用三元运算符来缩短代码. 这是我的原始代码: if ($type = "recent") { $OrderType = "sid DESC";} elseif ($type = "pop") { $OrderType = "counter DESC";} else { $OrderType = "RAND()";} 如何在代码中使用三元运算符而不是ifs / elses? $O
我正在尝试使用三元运算符来缩短代码.

这是我的原始代码:

if ($type = "recent") {
    $OrderType = "sid DESC";
} elseif ($type = "pop") {
    $OrderType = "counter DESC";
} else {
    $OrderType = "RAND()";
}

如何在代码中使用三元运算符而不是ifs / elses?

$OrderType = ($type = "recent") ? "sid DESC" : "counter DESC" ;

这是我尝试的代码,但不知道如何添加“elseif部分”.

这被称为三元运算符;-)

你可以使用其中两个:

$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.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读