What’s nice about PHP (among other things) is that code blocks can easily be nested inside the HTML of a page. This way you in insert dynamic content just like that. Of course you can also go the other way and echo out HTML via PHP.

My simple rule is: When you have a clear overweight of one or the other use this as your main code and nest-in the other.

This makes source code way more readable than, for example, when you have orgies of opening and closing PHP tags inside “some” HTML tags!

Let me give you an example (do you recognize where it’s from?).

Original Code

<?php if (have_posts()) : ?>
<?php while (have_posts()) : the_post(); ?>
<div>
<?php the_content('Read the rest of this entry &raquo;'); ?>
</div>
<?php endwhile; ?>
<?php else : ?>
 <b>Not Found</b>
<?php _e("Sorry, but you are looking for something that isn't here."); ?>
<?php endif; ?>

Cleaned up code

<?php
if( have_posts() ) {

  while( have_posts() ) {
    
    the_post();

    echo "<div>\n";

    the_content( 'Read the rest of this entry &raquo;' );

    echo "</div>\n";

  }
}
else {
  
  echo "<b>Not Found</b>\n";
  echo __( 'Sorry, but you are looking for something that isn't here.' );

}
?>

Well, I’ve also done some more formatting (according to my coding standard) and replaced the (in my mind) horrible and old-school : ENDIF ENDWHILE grammar. But you get my point, right?

When you’re writing new code, always keep that in mind. And if you’re refactoring old (legacy) code this cleaning up should be your absolute first step!

About these ads