Short PHP IF-Else Statements (Shorthand IF)

November 4, 2009 · Posted in PHP 

Funny thing is I have been working in PHP for years, but only with the prevalence of CMS’s have I required short code for PHP, I have always just typed things out in full. These shortened PHP conditional statements are called ternary operators, and I find them most useful when popping code into a CMS code block, otherwise I generally code stuff in full for legibility.

If you look at the PHP manual they give you the following alternative syntax which is really not that compact:

<?php
## all examples start with $x having a value of 3 ##
if ($x == 3):
echo "X is equal to 3";
else:
echo "X is not equal to 3";
endif;
?>

And that if and elseif … endif structure is fine, but what about one line alternative code for a PHP if statement:

<?php if ($x == 3): echo "X is equal to 3"; else: echo "X is not equal to 3"; endif; ?>

But still this is not that efficient, the following two versions give nice compact code the first for just printing the value:

<?php echo ($x == 3)? "X is equal to 3" : "X is not equal to 3"; ?>

and the second allocates the string value to $y, dependent on the short if statement, and then prints:

<?php $y = ($x == 3)? "X is equal to 3" : "X is not equal to 3" ; ?>
<?php echo $y ; ?>

And of course if all you want to do is print one thing’s value dependant on its not being blank or zero:

<?php echo ($z)? $z : "" ; ?>

Nice short if statement, have I missed anything?

The PHP manual does have a couple of points if you scroll down on this page. The most notable is “avoid “stacking” ternary expressions”; if you want your code to be readable dont nest ternary conditional statements.

  • Google Bookmarks
  • Digg
  • del.icio.us
  • Twitter
  • Technorati
  • Facebook
  • Reddit
  • Mixx
  • email
  • RSS

Comments

One Response to “Short PHP IF-Else Statements (Shorthand IF)”

  1. [...] This post was mentioned on Twitter by Duncan Moore, Web Tech Mech. Web Tech Mech said: @NookDigital Cool hey that is my summary of how to Shorten PHP IF Statements – http://bit.ly/2iUvXi [...]

Leave a Reply