PHP Tutorial : If condition in the short way (shorthand if)
May 21, 2009 Basic PHP
Do you know basical php if() condition right? Yeah, right. Everybody does. To tell the truth, without a comparison operator a language would not be qualified as “programming language” (that’s why HTML is a markup language and not a programming language: it can not do comparisons and alter the program flow according to their results).
But enough theory, this is a beginner’s blog so let’s have a look at a quicker way to do comparisons:
<?php $a=1; $b=3; $c = $a+$b; //THE SHORT WAY COMES print $c == 3 ? "yes $c = 3" : "no $c != 3"; //THE "COMMON" WAY SAME THING if($c ==3) { print "yes $c = 3"; }else{ print "no $c != 3"; } ?>
This is quite handy, in PHP, when you have a single line of HTML and need to print out a different tag according to the value a variable has. Something like:
echo $registered ? ‘‘.$username.’‘ : $username;
That only makes the link live if the user is registered and prints out the username with no link if not. Remember the first value is the one used if the condition is true.
In ‘C’ the ternary operator may provide huge speed gains, but in PHP it is more a way to make the code less cluttered and shorter.
Tags: if, if condition, if function, php if, php ternary comparison, php ternary operator, short if, shorthand if


June 13th, 2009 at 6:44 am
Would have been more useful to refer to it in its more widely-known name: shorthand if. Bit better for some google visits I mean.
June 13th, 2009 at 7:07 am
hmm didn’t know that name but I added that tag too, thanks for your time
November 25th, 2009 at 4:01 pm
Actually called a ternary comparison operator.
But hey you got good Google rankings for this anyway.