PHP Tutorial : If condition in the short way (shorthand if)

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.

3 Responses to “PHP Tutorial : If condition in the short way (shorthand if)”

  1. bogdan Says:

    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.


  2. admin Says:

    hmm didn’t know that name but I added that tag too, thanks for your time


  3. Ternary Says:

    Actually called a ternary comparison operator.

    But hey you got good Google rankings for this anyway.


Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>