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?
$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.
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
This is called the ternary operator ;-)
You could use two of those :
This can be read as :
$type
is'recent'
'sid DESC'
$type
is'pop'
'counter DESC'
'RAND()'
A couple of notes :
==
or===
; and not=
()
, to make things easier to readAnd, as a reference about the ternary operator, quoting the Operators section of the PHP manual :