Scott Klarr Jr
Ternary PHP short-hand IF/Else statement
Posted On Jan 10, 2008 at 5:16 pm
Lightweight IF Syntax
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";
}
This topic has the following tags:
Last 5 Linkbacks
- Oct 18, 2009www.millibit.com



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.
Bill Aug 13, 2009
I am not gay
Scott Klarr Aug 14, 2009
Uh... thanks for sharing?
Matt Nov 05, 2009
I agree using your first example where possible in all of your code.
But, using nested Ternary, simply makes the construct unreadable and prone to possible bugs. And if not bugs, completely a mess to try and read for other programmers.
So, I definitely find the second example, 'interesting' if nothing else, but would never use it in production code.
i am Programmer Nov 18, 2009
This technique make me easy. i love it .
Duncan Nov 25, 2009
I Agree with Matt, that the nested ternary is a little difficult to read. i usually only use this format when I am coding in a box, like a Wordpress snippet or Drupal wodjit (not a technical term).
My own summary on the topic: Short PHP statements
Lyman Jan 04, 2010
Quick and straight to the point. Thank you.