Posts Tagged ‘while’

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.

Fastest type of loop

Saturday, June 28th, 2008

In PHP, there are a number of loops available for you to use. There are while loops, do-while loops, and for loops. To see which one of these were fastest, I used each of them to perform 100,000,000 iterations. These are the loops which I used:

while(++$a<100000000){}

for(;++$a<100000000;){}

do{}while(++$a<100000000)

Here are my results:

while(++$a<100000000){}: 15.519 seconds
for(;++$a<100000000;){}: 17.577 seconds
do{}while(++$a<100000000): 13.744 seconds

As you can see, my results show that a do-while loop is 21.81% faster, compared to a for loop.