PHP’s Alternate Control Structure Syntax

By  on  

If you've ever had the pleasure experience of digging through WordPress' code, you've probably run into PHP's alternate control structure syntax. An example of this can be seen in the following code:

$code = 3;
if($code == 1):
	echo 'The process succeeded.';
else:
	echo 'The process failed.';
endif;

The same works with while, for, and foreach loops, as well as the switch statement:

$items = array('MooTools','PHP','CSS');
foreach($items as $item):
	echo $item;
endforeach;

Should I Use This? When?

Whether or not to use this syntax is completely up to you -- it really depends on your coding style and what you do (or don't) consider readable. I see this syntax used most often when many control structures are used within the same block of code; the "end____" syntax makes it much more apparent which structure you're ending (as opposed to simply coding "}"). I also see this syntax used more frequently than traditional control structure syntax when PHP code is closely embedded in HTML code.

What Do You Think?

I'd love to hear what you have to say about this syntax. I've begun using this alternate syntax more and tend to like it...possibly for the novelty of it. Many people have told me they hate it while others find it more readable. What do you think?

Recent Features

Incredible Demos

  • By
    Hot Effect: MooTools Drag Opacity

    As you should already know, the best visual features of a website are usually held within the most subtle of details. One simple trick that usually makes a big different is the use of opacity and fading. Another awesome MooTools functionality is...

  • By
    Create Twitter-Style Dropdowns Using jQuery

    Twitter does some great stuff with JavaScript. What I really appreciate about what they do is that there aren't any epic JS functionalities -- they're all simple touches. One of those simple touches is the "Login" dropdown on their homepage. I've taken...

Discussion

  1. xpix

    from Codeigniter’s manual:

    To minimize the PHP code in these files, and to make it easier to identify the code blocks it is recommended that you use PHPs alternative syntax for control structures and short tag echo statements. If you are not familiar with this syntax, it allows you to eliminate the braces from your code, and eliminate “echo” statements.

  2. I try to ran away as fast as possible from this style of syntax where-ever possible with the exception of templates. I think that in the soup of HTML, the extra pointers of which block is ending is very useful. I think that I learnt that methodology from the Smarty templating engine.

  3. I totally agree with XPIX: I find this syntax very useful when I am embedding php fragments into an html page (or a view when I use a MVC framework); that way is easier to spot and ENDIF amongst a tenths of closing curly bracket!!!

  4. I tend to use the alternative syntax in my view scripts. This is to try and keep the mark-up as clean as possible. That said, if I need to do any nesting, I usually abandon the alternative syntax, due to the benefits of IDEs matching braces.

  5. When I first saw the syntax it seemed out of place in a C family syntax, but I agree, it’s definitely more declarative when spaghettied together with a bunch of markup. It’s far more readable than finding a random…

    <?php } ?>

    …in the middle of some script, 50 lines from the opening brace.

    @xpix Shorthand printing (<?= $var ?>) is a convenient syntax, but be careful because not all php.ini configurations allow it. You could find yourself refactoring a lot of code if you have a host that doesn’t approve….

  6. The IDE / matching braces factor is huge. Good point.

  7. Chuck

    I have been using the alternative syntax a lot over the past year. I find it easier to go back to and scan. If you work in a CMS like joomla, modx, etc. the alternative syntax should also be easier for the newbies.

  8. I’ll continue the general agreement that the endif/endforeach style is well suited for templating, where the start and end of blocks is made more apparent.

  9. And of course you could complete it with something like this:

    <?php
    $items = array('MooTools','PHP','CSS');
    ?>
    <?foreach($items as $item):?>
    <!-- Many HTML stuff -->
        <?=$item;?>
    <!-- even moar -->
    <?endforeach;?>
    
  10. I have varied inconsistently between } and end__; depending on what’s already in the code I edit. I have found some content management systems though, which allow embedded php in content regions but then choke on, or html-entity convert embedded braces.

    So the alternate syntax is more reliable imo, I just need to get into the good habit of converting braces to it.

  11. It’s not just wordpress. If you look at compiled php code from smarty templates, you’ll also see it.
    I’ve been using this alternate syntax for some time. Before, I would just use something like:

    } // if

    to close an if block if it was somewhat long.
    The only drawback I see is the matching highlighting in editors (I use vim), but I think I can live without it.

  12. Dave,

    I love using this particular brand of PHP coding style. However, when asked about its validity in HTML templates, a friend of mine once told me that something like this:

    <?php foreach ($this->items as $item) : ?>
    <div><?php echo $item->name; ?></div>
    <?php endforeach; ?>

    while, pretty to read, is somewhat wasteful because of the constant opening and closing of the PHP tag (which calls the PHP engine each time). Not sure how I feel about the tradeoff yet…

  13. I like to stick to the same coding principles throughout all my code, and I use Bruno’s convention:

    } //while

    } //if $qry

  14. Sheldon McGee

    Having multiple ways to write the same code is confusing sometimes but so are all those meaningless curly braces . . . this reminds me of the syntax for VB and reminds me what I miss about VB.

  15. emceha

    My style:

    } //end foreach

    Word “end” makes code easier to scan for me.

  16. Some designers are (even if they know some HTML) frightened to death by curly braces. ;)

    So if I work together with a non-coding designer, I usually use the alternative syntax in my templates. The guys really appreciate this, because it just looks “less scary”.

  17. I’ll pretty much +1 the styles of:

    Curly braces when in full-blown PHP mode. IDE matching braces and comments allow me to keep track easily.
    Alternate syntax of PHP functions (while, foreach…) in templates and views for easier code.
    No use at all of shorthand echo statements, due to possible incompatibility, and I’ve heard it will be deprecated in future versions of PHP (don’t know of a reputable source of that one at this time – can anyone confirm?)

  18. Simon

    Same as Bruno and Adriaan, I prefer to use
    } //end foreach
    or
    } //end if
    and so on.
    But as we can see in the comments it’s mostly a choice of readability (is this word even english ? xD ).
    By the way, I see a lot of people talking about Smarty. I really like this template engine but never saw an interesting article or advanced tutorial about it (or even a real performance benchmark from this century). I would really be interested in such articles. Just saying David… :p

    P.S: Damn I just had to go backwards in the browser because I forgot to type my email address. I thought that I had to write the comment again but no… I don’t know if it’s thanks to your coding but anyway, thanks David xD

  19. Hey,
    thanks for the inspiration. Especially the idea with
    } // end if
    is really usefull!

    I only use php when I work with wordpress and I really love the ‘simplicity’ of the code blocks with :

    Nice Blog here David … I read many times and I already found a lot of good examples for my work or just some interesting stuff to experiment with.

    Thank you!

  20. } // end if

    this is best one

  21. I personally go with } , but I may add the comments after it from now on…

    Apart from the IDE convenience, it makes it so much easier to scan through code, because } is much quicker to read than endif; especially if code is tab spaced correctly.

    Mind you, when I code in WordPress, I try to maintain consistency and use endif; but I was very resistant to start with! You get used to it though.

  22. I discovered this alternate structure some time ago, and basically do similar to what Chris said a few comments back, for for slightly different reasons.

    If I’m working on a project with a designer who’s not very familiar with code, and the designer may need to tweak a view file or a WordPress template, then I use the alternate style throughout those types of files for the project. It makes their life easier, and it’s no bother to me either way, so why not :)

  23. I only use the alternatives when I am placing php into HTML, while as aaron said it is wasteful in processing, but I use APC as a bit cacher so my pages still loads pretty fast.

  24. my favorite code editor doesnt show the blocks correctly… so probaby not a good idea for me…

  25. I find this syntax very similar to the syntax of Ruby, and I love Ruby syntax. On that note I try my hardest to not have to use the curly brackets, to many of them gets very confusing.

  26. Kirara

    I preffered this syntax when I started with PHP and then abandon it because curly brackets was better supported in my code editor (highlighting pairs, etc.)

  27. Nathan Bishop

    First of all love the website, easy to navigate and great articles. I’m relatively new to PHP (about a year) so my input might not be warranted, however, I use curly brackets for complete php files (where I omit the closing tag ?>) and use the alternate syntax in my HTML files. I don’t like having a closing bracket randomly placed anywhere in my HTML.

  28. Chris

    Old thread, but I wanted to add: I combine the two, as a few other posters have mentioned. I like the structure of the curly brace, plus the mentioned IDE features. I also avoid shortcuts of any sort, in favor of being explicit. I don’t care if my code is short — that’s not what I’m getting paid for.

    The big advantage of alternate syntax is that it does make it clear when a block is ending. So, the combination approach takes the best of both worlds:

    if ($conditional === true) {
        foreach ($something as $item) {
    
            // do something in the loop
    
        } // end foreach $something
    } // end if $conditional
    

    Of course, I only do this on longer blocks.

  29. JH

    Like @Chris said above, this is old but I thought I give my opinion anyway.

    I absolutely hate the alternate syntax. Some people say it’s easier to read, and find the end of control structures, that’s bunk, what could be easier than clicking inside of any matched set of braces and clicking the IDE button to highlight the entire thing, and then collapsing it if you want to not worry about something and see how it fits in to the overall code easier? This is completely impossible using the alternate syntax, and instead you need to actually find that end….., and manually select the entire block if you want to collapse it. If you really need an end just add a comment } // end if whatever, as Chris gave in his example, something that I do at the end of almost every control structure that spans more than 3 lines of code.

    Another thing I absolutely hate is the constant opening and closing of PHP on every line of code. Just another eyesore that makes code harder to read and work on. Causes additional processing and adds unnecessary white-space to the output. I had never seen this before until I started working on WP.

    The last thing I’ve started seeing is using alternate syntax for arrays in PHP like that used in JS

    $array = [......]

    instead of

    $array = array(.....);

    You saved typing 5 characters and all you managed to do is throw up an error in my IDE because it does not understand what this means. Seriously, you’re worried about 5 characters but then you’ll turn around and do something like open and close php on every dang line adding 9 unnecessary characters to every line of code.

    What it boils down to is that people are just doing what other people do and what they are given as examples. Instead, take a stand an give better examples. Stop following the crowd, the crowd is invariably wrong 99% of the time. Not using these things has far more benefit than any benefit you may think using them has.

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!