News Flash

Great little tool for generating CSS3: http://css3generator.com by @randyjensen

Blog:

5 August 2009

Tip for Streamlining Your PHP if(statements)

By 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.

41
CSS3 Online Conference March 22nd 2010 banner ad

41 Comments

Have your say:

Sign Up to our Newsletter

Enter your e-mail address below to receive regular updates on web design, web development and web business. Subscribe today and receive a free 44 page PDF "Designing Web User Interfaces" by Ryan Singer of 37signals.

Subscribe to the Think Vitamin articles RSS feed

HTML5 Online Conference April 12 2010

News

Twitter

Follow us on Twitter

Subscribe

Article Subscribers

Feedburner blog subscriber indicator

News Subscribers

Feedburner blog subscriber indicator

Subscribe by Email

You can receive Think Vitamin updates via email. Just pop your email address in the box below and click the arrows.

Subscribe by RSS

You can also receive new Think Vitamin posts via your RSS feed reader

Subscribe RSS Think Vitamin is a proud member of the Smashing Network

Ads Via The Deck