简体   繁体   English

如何在PHP中使用三元运算符代替if-else

[英]How to use ternary operator instead of if-else in PHP

I'm trying to shorten my code using the ternary operator. 我正在尝试使用三元运算符来缩短代码。

This is my original code: 这是我的原始代码:

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

How can I use the ternary operator in my code instead of if s/ else s? 如何在代码中使用三元运算符而不是if s / else s?

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

This is the code I tried, but have no idea how to add an “ elseif part” to it. 这是我尝试过的代码,但不知道如何向其中添加“ elseif部分”。

This is called the ternary operator ;-) 这称为三元运算符 ;-)

You could use two of those : 您可以使用其中两个:

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

This can be read as : 可以理解为:

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


A couple of notes : 一些注意事项:

  • You must use == or === ; 您必须使用===== ; and not = 而不是=
  • It's best to use () , to make things easier to read 最好使用() ,使内容更易于阅读
    • And you shouldn't use too many ternary operators like that : it makes code a bit hard to understand, i think 而且您不应该使用太多这样的三元运算符:我认为这会使代码有点难以理解


And, as a reference about the ternary operator, quoting the Operators section of the PHP manual : 并且,作为三元运算符的参考,引用PHP手册Operators部分

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. 用括号括起三元表达式是一个好主意。

I'd suggest using a case statement instead. 我建议改用case语句。 it makes it a little more readable but more maintainable for when you want to add extra options 当您要添加其他选项时,它使它更具可读性,但更易于维护

switch ($type)
{
case "recent":
  $OrderType =  "sid DESC"; 
  break;
case "pop":
  $OrderType =  "counter DESC"; 
  break;
default:
   $OrderType =  "RAND()"; 
} 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM