views:

180

answers:

2

hey guys

i need to shorten or better to say ., harden my codes

this is my original code :

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

now how can i use markers like this :

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

i tried but i didnt know how to write elseif in operators

+7  A: 

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 =
  • 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.

Pascal MARTIN
+1  A: 

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()"; 
} 
Mauro
The question is about ternary operators, but I agree, in this case, switch makes a lot more sense.
luminarious
Ah well, the question is to "shorten or better" - less lines doesnt always == better; I like ternary operators but sometimes they just arent the right thing to use.
Mauro