如何在PHP中使用三元运算符代替if-else [英] How to use ternary operator instead of if-else in PHP

查看:384
本文介绍了如何在PHP中使用三元运算符代替if-else的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用三元运算符来缩短代码.

I’m trying to shorten my code using the ternary operator.

这是我的原始代码:

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

如何在代码中使用三元运算符而不是if s/else s?

How can I use the ternary operator in my code instead of ifs/elses?

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

这是我尝试过的代码,但不知道如何在其中添加"elseif部分".

This is the code I tried, but have no idea how to add an "elseif part" to it.

推荐答案

这称为三元运算符;-)

您可以使用其中两个:

$OrderType = ($type == 'recent' ? 'sid DESC' : ($type == 'pop' ? 'counter DESC' : 'RAND()'))

这可以理解为:

  • 如果$type'recent'
  • 然后使用'sid DESC'
  • 其他
    • 如果$type'pop'
    • 然后使用'counter DESC'
    • 其他使用'RAND()'
    • if $type is 'recent'
    • then use 'sid DESC'
    • else
      • if $type is 'pop'
      • then use 'counter DESC'
      • else use 'RAND()'


      一些注意事项:


      A couple of notes :

      • 您必须使用=====;而不是=
        • You must use == or === ; and not =
          • The first two ones are comparison operators
          • The last one is the assignment operator
          • 您不应该使用太多这样的三元运算符:我认为这会使代码有点难以理解


          并且,作为有关三元运算符的参考,引用 运算符 PHP手册的部分:


          And, as a reference about the ternary operator, quoting the 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.

          这篇关于如何在PHP中使用三元运算符代替if-else的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆