I’m trying to shorten my code using the ternary operator.
This is my original code:
if ($type = \"recent\") {
$OrderType = \"sid DESC\";
} elseif
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()";
}
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 :
$type
is 'recent'
'sid DESC'
$type
is 'pop'
'counter DESC'
'RAND()'
A couple of notes :
==
or ===
; and not =
()
, to make things easier to read
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.