LearnTip for Streamlining Your PHP if(statements)

Recently I have been working on a WordPress plugin for Think Vitamin which necessitated getting back into the swing of PHP.

Whilst getting my head around how to create the plugin I started to delve into some of the core WordPress files and came across an unfamiliar yet syntactically sweet PHP control structure. It’s a simple if statement used in a file that combines PHP and HTML.

Old version:

<?php if(<your evaluation here>) { ?>
// Output
<?php } else { ?>
// Output
<?php }; ?>

New version: Much easier to read

<?php if(<your evaluation here>): ?>
// Output
<?php else: ?>
// Output
<?php endif; ?>

It also works on “for” and “while” loops as well as “elseif”.

I have never been a fan of combining HTML and PHP, preferring the separation of code and HTML offered by template engines like Smarty, but I could be persuaded. To me this is syntactically much clearer and in my opinion wouldn’t be too difficult for non “coders” working on your project to grasp.

Here are two further examples from WordPress:

<?php if (have_posts()) : while (have_posts()) : the_post(); ?>

<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
// Output
<?php endwhile; else: ?>
// Output
<?php endif; ?>

There are always new things to learn and learning from other people’s code is a great place to start.

86 Responses to “Tip for Streamlining Your PHP if(statements)”

  1. personally I prefer the older trick πŸ˜‰

  2. helium on July 23, 2010 at 8:02 am said:

    MVC? seperate display elements?

    Personaly i prefer using full:

    if($bla = ‘blah’)
    {
    //code
    }

    just for readability and flow ^_^

  3. helium on July 23, 2010 at 8:02 am said:

    MVC? seperate display elements?

    Personaly i prefer using full:

    if($bla = ‘blah’)
    {
    //code
    }

    just for readability and flow ^_^

  4. This streamlining trick actually sucks. It doesn’t read easier at all but obfuscates the logics in some way. Highly UNrecommended.

  5. This streamlining trick actually sucks. It doesn’t read easier at all but obfuscates the logics in some way. Highly UNrecommended.

  6. When embedding in HTML, this is definitely the way to go. Personally, I don’t see the point in using Smarty – it’s no easier to read than PHP when it’s done like this, making it an unnecessary overhead in my mind.

    • Keir Whitaker on August 6, 2009 at 6:32 pm said:

      I totally understand that viewpoint. For me having the ability to modify variables easily, output form elements from arrays, have filters and the number of plugins available made Smarty work for me. But yes you are right, it still takes time to learn the syntax and get your head round how it works.

      As I think the comments have highlighted it’s really down to personal preference and your own coding style πŸ™‚

      • Absolutely! As long as what you write is clear and well-documented, it really doesn’t matter what you use.

        Further to your comment, I prefer leaving the modification of variables out of the HTML parts of my code. I’d simply do whatever was needed to the variable to the place that was calling it. I really don’t like to have anything more than if ($blah === false) and foreaches in my HTML but then, as you say, it’s all down to preference. Like most, I’ve certainly taken my style of coding through many iterations before arriving at something I find easy to return to and maintain!

  7. When embedding in HTML, this is definitely the way to go. Personally, I don’t see the point in using Smarty – it’s no easier to read than PHP when it’s done like this, making it an unnecessary overhead in my mind.

    • Keir Whitaker on August 6, 2009 at 6:32 pm said:

      I totally understand that viewpoint. For me having the ability to modify variables easily, output form elements from arrays, have filters and the number of plugins available made Smarty work for me. But yes you are right, it still takes time to learn the syntax and get your head round how it works.

      As I think the comments have highlighted it’s really down to personal preference and your own coding style πŸ™‚

      • Absolutely! As long as what you write is clear and well-documented, it really doesn’t matter what you use.

        Further to your comment, I prefer leaving the modification of variables out of the HTML parts of my code. I’d simply do whatever was needed to the variable to the place that was calling it. I really don’t like to have anything more than if ($blah === false) and foreaches in my HTML but then, as you say, it’s all down to preference. Like most, I’ve certainly taken my style of coding through many iterations before arriving at something I find easy to return to and maintain!

  8. Billy Girlardo on August 6, 2009 at 12:15 pm said:

    I like braces because it keeps code compartmentalized.

  9. Billy Girlardo on August 6, 2009 at 12:15 pm said:

    I like braces because it keeps code compartmentalized.

  10. Jack Sleight on August 6, 2009 at 9:07 am said:

    I think it’s more of a personal preference than one being more streamlined and “easier to read” than the other. I personally prefer to use one style (curly braces) consistently throughout all code (templates. scripts, classes etc.).

  11. Jack Sleight on August 6, 2009 at 9:07 am said:

    I think it’s more of a personal preference than one being more streamlined and “easier to read” than the other. I personally prefer to use one style (curly braces) consistently throughout all code (templates. scripts, classes etc.).

  12. I picked this style from CodeIgniter, a PHP framework. It’s a real pleasure to write PHP code and combine it with HTML in view files. If you align code blocks correctly, it actually improves readability and you don’t need to mess with those curly brackets anymore (as far as output/view files are concerned, of course).

  13. I picked this style from CodeIgniter, a PHP framework. It’s a real pleasure to write PHP code and combine it with HTML in view files. If you align code blocks correctly, it actually improves readability and you don’t need to mess with those curly brackets anymore (as far as output/view files are concerned, of course).

  14. Cristiano Rastelli on August 6, 2009 at 8:09 am said:

    An even shorter sintax (to be enabled in the php.ini file) is called “short tags” which makes code even more readeable:

    <? if(): ?>
    // Output

    // Output

    and using ternary operators you can do:

    <?= () ? “Output #1” : “Output #2”; ?>

    instead of using the old-style “echo” command.

    • Tim Sheehan on August 22, 2010 at 11:56 pm said:

      PHP short tags have been deprecated. This will no longer work in newer versions of PHP and isn’t considered a best practice πŸ™

  15. Cristiano Rastelli on August 6, 2009 at 8:09 am said:

    An even shorter sintax (to be enabled in the php.ini file) is called “short tags” which makes code even more readeable:

    <? if(): ?>
    // Output

    // Output

    and using ternary operators you can do:

    <?= () ? “Output #1” : “Output #2”; ?>

    instead of using the old-style “echo” command.

  16. bogphanny on August 5, 2009 at 11:56 pm said:

    it is worth noting that using the colon syntax for Else-If blocks requires “elseif”, rather than “else if” (which otherwise works if you use the curly brace syntax)

  17. bogphanny on August 5, 2009 at 11:56 pm said:

    it is worth noting that using the colon syntax for Else-If blocks requires “elseif”, rather than “else if” (which otherwise works if you use the curly brace syntax)

  18. Martin F on August 5, 2009 at 8:07 pm said:

    Any person on my team doing that would be shot. Twice. And then fired. Any designer worth his salt knows basic PHP, using alternative syntax in templates is going to do nothing but alienate those designers who have taken the time to actually learn basic PHP.

    As for your next tutorial on the ternary operator, be _very_ careful with it.

    echo true ? ‘true’ : ‘false’;

    might be obvious, but what about

    echo true ? ‘true’ : false ? ‘t’ : ‘f’;

    Should be ‘true’ right? No, it’s ‘t’ yeah, go figure… it’s completely reverse from normal PHP in that it’s evaluated from left to right. I see tons of people in various IRC channels and forums who don’t get that. And people will nest them unless you specifically tell people it’s a bad thing.

    • I don’t see how it would alienate a designer who has learnt basic PHP. In fact they still need to understand basic programming to make sure they understand the criteria and include the correct content in the right places.

      I’m not saying I’m right for using it and your wrong, however I am saying that I’m not wrong for using it. As I said above it is all about consistency, the worst thing to do is chop and change all over the place.

    • Keir Whitaker on August 5, 2009 at 8:27 pm said:

      I think we have different expectations from designers we collaborate with. I have worked closely with designers who have no concept of server side languages but produce amazing work. I also don’t really think the syntax is that different that someone who has learnt PHP wouldn’t understand it.

      My comment about the ternary tutorial was very much tongue in cheek, I always have to look that one up.

    • Jens Ljungblad on August 5, 2009 at 9:20 pm said:

      For your information, Zend Framework, Symfony, CakePhp, Codeigniter, ALL the major Php frameworks advocate and promote the alternative syntax for view templates. Your statement doesn’t make any sense, and pretty much makes you look like you’ve been living under a rock for the past five years. Languages evolve. Get with the times.

    • I totally agree with Jens Ljungblad. It seems that you’ve never used a decent PHP framework (if any at all). Don’t throw rocks at other people if you don’t even know if they’re really guilty.

      And do you seriously think that designers would get confused with this alternative syntax? Personally, I think a designer would get the idea in approximately 5 minutes if he was familiar with PHP.

  19. Sean Delaney on August 5, 2009 at 8:07 pm said:

    This coding style has been started by WordPress developer, Matt Mullenweg and it’s been adopted by other developers since.

    If you look at code snippets from magazines, books, on the web or even if your learning PHP at College, University or night classes, you’ll be taught the “old” way…

    Is there any test case’s completed to see if the “new” way is faster? I haven’t come across any.

    The post is nice but I personally don’t think it makes a difference IMHO even for non-coders and beginners!

    • Keir Whitaker on August 5, 2009 at 8:18 pm said:

      Spot on – I haven’t come across it in any PHP tutorials I have read.

      I am not sure if it’s faster, I just wanted to highlight an alternative syntax πŸ™‚

    • It’s been used in Drupal templates for years too. I’ve never really seen the point of using this alternative control structure but reading this post has highlighted the fact that it is slightly clearer in this particular case, ie. mixing PHP and HTML.

  20. Martin F on August 5, 2009 at 8:07 pm said:

    Any person on my team doing that would be shot. Twice. And then fired. Any designer worth his salt knows basic PHP, using alternative syntax in templates is going to do nothing but alienate those designers who have taken the time to actually learn basic PHP.

    As for your next tutorial on the ternary operator, be _very_ careful with it.

    echo true ? ‘true’ : ‘false’;

    might be obvious, but what about

    echo true ? ‘true’ : false ? ‘t’ : ‘f’;

    Should be ‘true’ right? No, it’s ‘t’ yeah, go figure… it’s completely reverse from normal PHP in that it’s evaluated from left to right. I see tons of people in various IRC channels and forums who don’t get that. And people will nest them unless you specifically tell people it’s a bad thing.

    • I don’t see how it would alienate a designer who has learnt basic PHP. In fact they still need to understand basic programming to make sure they understand the criteria and include the correct content in the right places.

      I’m not saying I’m right for using it and your wrong, however I am saying that I’m not wrong for using it. As I said above it is all about consistency, the worst thing to do is chop and change all over the place.

    • Keir Whitaker on August 5, 2009 at 8:27 pm said:

      I think we have different expectations from designers we collaborate with. I have worked closely with designers who have no concept of server side languages but produce amazing work. I also don’t really think the syntax is that different that someone who has learnt PHP wouldn’t understand it.

      My comment about the ternary tutorial was very much tongue in cheek, I always have to look that one up.

    • Jens Ljungblad on August 5, 2009 at 9:20 pm said:

      For your information, Zend Framework, Symfony, CakePhp, Codeigniter, ALL the major Php frameworks advocate and promote the alternative syntax for view templates. Your statement doesn’t make any sense, and pretty much makes you look like you’ve been living under a rock for the past five years. Languages evolve. Get with the times.

    • I totally agree with Jens Ljungblad. It seems that you’ve never used a decent PHP framework (if any at all). Don’t throw rocks at other people if you don’t even know if they’re really guilty.

      And do you seriously think that designers would get confused with this alternative syntax? Personally, I think a designer would get the idea in approximately 5 minutes if he was familiar with PHP.

  21. Sean Delaney on August 5, 2009 at 8:07 pm said:

    This coding style has been started by WordPress developer, Matt Mullenweg and it’s been adopted by other developers since.

    If you look at code snippets from magazines, books, on the web or even if your learning PHP at College, University or night classes, you’ll be taught the “old” way…

    Is there any test case’s completed to see if the “new” way is faster? I haven’t come across any.

    The post is nice but I personally don’t think it makes a difference IMHO even for non-coders and beginners!

  22. Personally I use a mixture of the 2.

    In blocks that are pure PHP I prefer the curly bracket approach (helps with code collapse)

    in files that have HTML I use the alternate syntax, also I have a rule that no HTML can be echoed (content is fine, but no tags!). This keeps things easier for frontend devs, who will need to edit the files.

    I guess the key is use what works for you, and perhaps more importantly be consistent throughout. Set some coding standards and stick with them. Document these standards to help keep them in mind ( perhaps that is another article altogether!)

    • Keir Whitaker on August 5, 2009 at 7:47 pm said:

      Nice approach πŸ™‚ I would be really interested to know how you document your coding standards (Word doc, HTML page). Would you be willing to share?

      • It varies depending on the project.

        For personal projects I find Google Docs works for me. Most of the time they are very basic and generally don’t change too much between projects (for obvious reasons :-))

        The guidelines cover both server side and front end, such as naming conventions for functions and variables, to how HTML element ids / classes should be defined (underscore, camelCaps, hyphen).

        At work (software dev) they are generally stored in a Lotus Notes DB, to allow for access control and such. I will point out that I don’t create these guidelines, I just follow them! These are also very in depth and talk about how to approach different situations.

        Like I say, they don’t need to be much, you just need to stick to them. It can make things so much easier for everyone involved, and also if you have to return to a project in the future.

  23. Personally I use a mixture of the 2.

    In blocks that are pure PHP I prefer the curly bracket approach (helps with code collapse)

    in files that have HTML I use the alternate syntax, also I have a rule that no HTML can be echoed (content is fine, but no tags!). This keeps things easier for frontend devs, who will need to edit the files.

    I guess the key is use what works for you, and perhaps more importantly be consistent throughout. Set some coding standards and stick with them. Document these standards to help keep them in mind ( perhaps that is another article altogether!)

    • Keir Whitaker on August 5, 2009 at 7:47 pm said:

      Nice approach πŸ™‚ I would be really interested to know how you document your coding standards (Word doc, HTML page). Would you be willing to share?

      • It varies depending on the project.

        For personal projects I find Google Docs works for me. Most of the time they are very basic and generally don’t change too much between projects (for obvious reasons :-))

        The guidelines cover both server side and front end, such as naming conventions for functions and variables, to how HTML element ids / classes should be defined (underscore, camelCaps, hyphen).

        At work (software dev) they are generally stored in a Lotus Notes DB, to allow for access control and such. I will point out that I don’t create these guidelines, I just follow them! These are also very in depth and talk about how to approach different situations.

        Like I say, they don’t need to be much, you just need to stick to them. It can make things so much easier for everyone involved, and also if you have to return to a project in the future.

  24. Russell Smith on August 5, 2009 at 7:23 pm said:

    It unfortunately has the nasty side effect of not being that easy to find the closing pair compared to the normal way, as your IDE can’t highlight the other end…

  25. Russell Smith on August 5, 2009 at 7:23 pm said:

    It unfortunately has the nasty side effect of not being that easy to find the closing pair compared to the normal way, as your IDE can’t highlight the other end…

  26. Despite that alternative control structures do exist in PHP for a long time (http://onlamp.com/pub/a/php/2001/05/03/php_foundations.html?page=1), i remember that there is a more or less significant performance difference between those structures. One should keep in mind that some are better (elseif) than others (else if) and that this might be more important in an enterprise environment than “good” coding style.

    I personally like that structures and think that WordPress is just doing fine by using those in their templates.

  27. Despite that alternative control structures do exist in PHP for a long time (http://onlamp.com/pub/a/php/2001/05/03/php_foundations.html?page=1), i remember that there is a more or less significant performance difference between those structures. One should keep in mind that some are better (elseif) than others (else if) and that this might be more important in an enterprise environment than “good” coding style.

    I personally like that structures and think that WordPress is just doing fine by using those in their templates.

  28. Funny, this is one of the first things I picked up from WordPress source and used in my own programing style. Thanks for sharing your thoughts πŸ™‚

  29. Funny, this is one of the first things I picked up from WordPress source and used in my own programing style. Thanks for sharing your thoughts πŸ™‚

  30. Adam Petrie on August 5, 2009 at 4:25 pm said:

    I agree, alternate syntax is very useful. Personally I have only ever mixed PHP and HTML, how would you propose NOT mixing the two?

    I’ve heard people discussing the use of echo, is that the preferred approach?

    Just curious.

    • Keir Whitaker on August 5, 2009 at 6:21 pm said:

      The main alternative is to look at using a template language which separates the templates from the code. The PHP and HTML are never truly separate, it’s just a different approach. As always it really depends on the context of your site, if it’s just a few pages it’s perhaps too much work to add in something like Smarty – pragmatism should sometimes win out πŸ™‚

  31. Adam Petrie on August 5, 2009 at 4:25 pm said:

    I agree, alternate syntax is very useful. Personally I have only ever mixed PHP and HTML, how would you propose NOT mixing the two?

    I’ve heard people discussing the use of echo, is that the preferred approach?

    Just curious.

  32. Krues8dr on August 5, 2009 at 4:15 pm said:

    Tags got stripped, that code should look like:

    {?php if($user) : /* if user */ }
    {?php if($loggedin) : /* if logged in */}
    Something
    {?php endif; /* if logged in */}
    {?php else : /* if not user */}
    Something else
    {?php endif; /* if user */}

  33. Krues8dr on August 5, 2009 at 4:15 pm said:

    Tags got stripped, that code should look like:

    {?php if($user) : /* if user */ }
    {?php if($loggedin) : /* if logged in */}
    Something
    {?php endif; /* if logged in */}
    {?php else : /* if not user */}
    Something else
    {?php endif; /* if user */}

  34. Krues8dr on August 5, 2009 at 4:13 pm said:

    I go one step further and use matching comment pairs on every block so that you can easily find the start and end set when nesting.

    Something.

    Something else.

    etc.

  35. Krues8dr on August 5, 2009 at 4:13 pm said:

    I go one step further and use matching comment pairs on every block so that you can easily find the start and end set when nesting.

    Something.

    Something else.

    etc.

  36. Do “non” coders still exist? And would you want to accomodate them?
    I guess that’s a different discussion, but once an XHTML template has been made dynamic with PHP, is there still much chance that a non-coder will have to edit the code?

    A more related question, would you mix PHP and HTML (as shown in the examples) or rather echo all the output in PHP, thus rather using “blocks” of PHP in your code? People often find echoing can make code less readable, but I guess mixing PHP and HTML code blocks can have the same effect on readability.

    • I’ve done both. It seems easier to me if you assign your output to a variable then echo that so you can get more readable code.

      $output = ”;
      $output .= ‘text here’;
      $output .= ”;

      echo $output;

    • Keir Whitaker on August 5, 2009 at 6:16 pm said:

      I think “non coders” exist. To clarify I am referring to those who might not be familiar with server side languages like PHP but are very involved in the build process of a site. I don’t really see any reason why they wouldn’t edit the templates.

      In terms of “echo” vs “code blocks” I think it’s down to personal preference. I have used both methods in the past. These examples are lifted directly from WordPress which doesn’t build up strings of HTML which are then echo’d out later in the page. In that context it works really well and has the added advantage that you don’t need to remember to escape strings. I also believe it is easier to follow what’s going on if the code blocks are in the template.

      It’s another post (perhaps) but that is why I like the approach of template engines like Smarty as they abstract the PHP code and use a very readable (IMO) syntax. I am a big fan of the Django template system which uses a similar approach.

  37. Do “non” coders still exist? And would you want to accomodate them?
    I guess that’s a different discussion, but once an XHTML template has been made dynamic with PHP, is there still much chance that a non-coder will have to edit the code?

    A more related question, would you mix PHP and HTML (as shown in the examples) or rather echo all the output in PHP, thus rather using “blocks” of PHP in your code? People often find echoing can make code less readable, but I guess mixing PHP and HTML code blocks can have the same effect on readability.

    • I’ve done both. It seems easier to me if you assign your output to a variable then echo that so you can get more readable code.

      $output = ”;
      $output .= ‘text here’;
      $output .= ”;

      echo $output;

    • Keir Whitaker on August 5, 2009 at 6:16 pm said:

      I think “non coders” exist. To clarify I am referring to those who might not be familiar with server side languages like PHP but are very involved in the build process of a site. I don’t really see any reason why they wouldn’t edit the templates.

      In terms of “echo” vs “code blocks” I think it’s down to personal preference. I have used both methods in the past. These examples are lifted directly from WordPress which doesn’t build up strings of HTML which are then echo’d out later in the page. In that context it works really well and has the added advantage that you don’t need to remember to escape strings. I also believe it is easier to follow what’s going on if the code blocks are in the template.

      It’s another post (perhaps) but that is why I like the approach of template engines like Smarty as they abstract the PHP code and use a very readable (IMO) syntax. I am a big fan of the Django template system which uses a similar approach.

  38. Nice tips for the if statements it looks very clean! I have yet to set up some PHP that way. If you are just setting a variable ternary operators are awesome.

    $var = ($i == 1) ? ‘if text’ : ‘else text’;

  39. Nice tips for the if statements it looks very clean! I have yet to set up some PHP that way. If you are just setting a variable ternary operators are awesome.

    $var = ($i == 1) ? ‘if text’ : ‘else text’;

  40. Josh Kendall on August 5, 2009 at 3:16 pm said:

    There are also Alternative Syntax options for Switch and Foreach. – http://us.php.net/manual/en/control-structures.alternative-syntax.php

    I first encountered the alternative syntax in a project where one developer had used them and the other did the “normal” curly brace method. I didn’t like the alternative syntax when I first saw it, but recently I forced myself to start using it. Its so much easier to find an endpoint for a specific if statement surrounded by other endif’s and endforeach’s than it is with curly braces (especially if the indentation is off).

  41. Nice tutorial, simple and useful tips

  42. Josh Kendall on August 5, 2009 at 3:16 pm said:

    There are also Alternative Syntax options for Switch and Foreach. – http://us.php.net/manual/en/control-structures.alternative-syntax.php

    I first encountered the alternative syntax in a project where one developer had used them and the other did the “normal” curly brace method. I didn’t like the alternative syntax when I first saw it, but recently I forced myself to start using it. Its so much easier to find an endpoint for a specific if statement surrounded by other endif’s and endforeach’s than it is with curly braces (especially if the indentation is off).

  43. Nice tutorial, simple and useful tips

  44. Paul Decowski on August 5, 2009 at 3:15 pm said:

    It’s called alternative syntax and it also worka with foreach.

  45. Paul Decowski on August 5, 2009 at 3:15 pm said:

    It’s called alternative syntax and it also worka with foreach.

  46. I personally was using this method for quite a while then found that while using TextMate it was difficult to follow and debug in larger applications so I went back to curly braces to allow for collapsing of individual segments.

    Anyone know of a program that can collapse these like TextMate does for the curly braces?

  47. I personally was using this method for quite a while then found that while using TextMate it was difficult to follow and debug in larger applications so I went back to curly braces to allow for collapsing of individual segments.

    Anyone know of a program that can collapse these like TextMate does for the curly braces?

Leave a Reply

Want to learn more about PHP?

Learn how to create dynamic websites using the back-end programming language, PHP.

Learn more