first_page the funky knowledge base
personal notes from way, _way_ back and maybe today

PHP: “Tip for Streamlining Your PHP if(statements)”; Keir Whitaker

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.

[http://carsonified.com/blog/dev/php/tip-for-streamlining-your-php-ifstatements/]

mod date: 2009-09-21T18:37:08.000Z