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

橙三吉。 提交于 2019-12-17 19:24:30

问题


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 ifs/elses?

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


回答1:


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'
  • 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
  • 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 :

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.




回答2:


I'd suggest using a case statement instead. 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()"; 
} 


来源:https://stackoverflow.com/questions/2705109/how-to-use-ternary-operator-instead-of-if-else-in-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!