PHP foreach() function

Okay, another everyday snippet of PHP code tweaked.

We all use the following


foreach($array as $item){

// Do something



Which works fine, sometimes the // Do something gets complicated with HTML


foreach($array as $item){

echo '<tr>';

echo '<td>'.$item->first_name.'</td>';

echo '<td>'.$item->last_name.'</td>';

echo '<td><a href="'. $item->name .'">'.$item->email.'</a></td>';

echo '</tr>';



After a while it gets messy and can be easy to have errors in your HTML which your editor might not pick up.

How about this for a solution – its an Alternative Form


foreach($array as $item) : ?>


<td><?= $item->first_name ?></td>

<td><?= $item->last_name ?></td>

<td><a href="<?= $item->email ?>"><?= $item->email ?></a></td>


<?php endforeach ?>

There are a few other ways but this reads really well. If you are looking to store the HTML as a variable before echoing it out have a look at ob_start(). However, creating chunks of HTML and passing them from place to another isn’t really good form – see separations of concerns ¬†and MVC


This also works for if() statments