Skip Navigation
Madison, Wisconsin
Powderkeg Web Design
April 4, 2014

Cut down on echoing out HTML with segregated loops

Nick
Nick
Cut down on echoing out HTML with segregated loops

Sometimes  you have to echo out a lot of html in PHP. Imagine getting a long list of results from a database query where you want to display the information on the page. You want to encase each item in a few div tags with classes along with a link and an image. To do this straight up, it would look something like this:

<?php 
foreach($results as $item){
 echo '<div class="item">'.$item->title.'<br />;
 echo '<div class="content">'.$item->content.'</div>;
 echo '<img src="'.$item->image.'" />';
 echo '<a href="www.google.com">'.$item->url.'</a>;
 echo '</div>';
}
?>

 That’s a lot of non formatted code and a lot of .’s to keep track of. Yes the code will work, but there is a better way to make it easier to read and modify. With the same information from above, we can instead code it out like this:

<?php
   foreach($results as $item):
?>
   <div class="item">
      <div class="item">
         <?php echo $item->title; ?>
         <br />
         <div class="content">
            <?php echo $item->title; ?>
         </div>
         <img src="<?php echo $item->image; ?>" />
         <a href="http://wwww.google.com">
            <?php echo $item->url; ?>
         </a>
      </div>
   </div>
<?php
   endforeach;
?>

That piece of code basically starts a foreach loop, then closes the php tag. It then renders your html code and ends the foreach in another php tag after it. This allows you to code out actual html code and format it a lot more easily. Then you just have to open up a php tag, echo out a specific piece of information, then close that php tag. You don’t have to concatenate  a bunch of statements, and it makes for cleaner code.

You can also do the same thing for for loops, if statements, and while loops. Just make sure you close anything you open or you will get yelled at by the server!

Nick Kalscheur

Nick Kalscheur

Lead Developer