Previous Post: USB 3 Revealed - Promises of 10x speeds!
Next Post: Linux: Automatically backup your mysql databases daily
Jan 10, 2008 at 5:16 pm - 2 Comments
Any programmer will agree that the IF/ELSE statements are a fundamental part of any language. The basic syntax is pretty universal between languages but many dont realise that there is a shorthand version that allows switching to be done inline.
The syntax is simply statement ? if-true : if-false
$variable = (statement) ? "return if true" : "return if false";
Compared to
if(statement) {
$variable = "return this if true";
}
else {
$variable = "return this if false";
}
As you can see, you save a lot of coding by using this lightweight syntax for simple IF/ELSE statements. It can also be used inline within strings which is where I find the most benefit of using it. Here is an example that has a real world use for a simple output that changes between "there is 1 item", "there are X items", and "there are no items" using multiple statements.
$text = "There ".
($total==1 ? "is 1 item" :
"are ".($total == 0 ? "no items" : "$total items")
);
Compared to:
if($total==0) {
$text = "There are no items";
}
else if($total==1) {
$text = "There is 1 item";
}
else if($total > 0) {
$text = "There are $total items";
}

Freddy Apr 03, 2008
FYI this is called a 'ternary' comparision
Sean Dec 27, 2008
Thanks for making this so search-able. I've seen this syntax many times before but never paid too close attention to it until I actually wanted to use it - very clear description I appreciate the help.