Posts Tagged ‘retrospect’

PHP:Use Less PHP And More HTML With Alternative Syntax

Monday, June 30th, 2008

When PHP is tightly intertwined with HTML it can be awful to lay your eyes upon. Many years ago, while with a previous employer, the development staff and I believed it was a sin to use straight HTML in PHP files. We believed every file ending in a .php extension could only contain PHP. In retrospect, I don’t know why we ever did this, but I have seen other groups adhere to such rules as well. This style made what should have been simple HTML far more complex that it had to be.

Over the past few years the style in which developers are writing PHP to output HTML has shifted quite a bit.

Example 1: No Alternative Syntax, and a Lot of PHP.

<?php
echo “<table size=\”100\”>\n”;
echo ” <tbody>\n”;

if($displayResults) {

while($row = mysql_fetch_assoc($result)) { ?>
echo “<tr>\n”;
echo “<td>” . htmlentities($row['id']) . “</td>\n”;
echo “</tr>\n”;
}

}

echo “</tbody>\n”;
echo “</table>\n”;

?>

This is typical to what I’ve seen in a number of PHP applications. Though this is a simple example, I am sure you can appreciate how this method of outputting mostly html can grow out of control. It requires significantly more developer brain power to determine the code’s purpose than the example below.

Example 2: Less PHP Paired With Alternative Syntax

<table>
<tbody>
<?php if($displayResults): ?>
<?php while($row = mysql_fetch_assoc($result)): ?>
<tr>
<td><?php echo htmlentities($row['id']); ?></td>
</tr>
<?php endwhile; ?>
<?php endif; ?>
</tbody>
</table>

Here in example 2 the same functionality is achieved by using PHP alternate syntax and less output statements. As you can see, this fashion of interweaving PHP and HTML can go a long way to increase code readability.