Cleaner Embedded PHP If/Foreach Syntax
In the last decade I’ve seen the wide variety of ways in which PHP has been used to control the output of HTML. Whether you’re using a template system like Smarty or you’re simply using PHP itself as a template language there are many different ways of combining the two.
Unfortunately many of them are messy. Years ago I decided that embedding any logic that had to be within the html was better than printing out all of your html using PHP. With the addition of using short tags for printing, you could usually do just fine.
When it comes to a loop of some kind that has to be embedded within a condition, it’s always ugly. For example, the following code was taken from a recent web application. This is hard to look at, and is even worse when you combine the HTML with it.
<?php
if(!empty($array)){
foreach($array as $item){
?>
...data goes here
<?php
}
} else { ?>
... no results message
<?php } ?>
Too many lines, too many indentation mismatches, HTML and PHP indentation conflicts, etc. I’m always in search of cleaner, more efficient ways of doing things.
After some time of playing around with various syntax choices and embedding needs, I’ve found what I believe to be the best method:
<?php if(!empty($array)): foreach($array as $item): ?> ...data goes here <?php endforeach; else: ?> ... no results message <?php endif; ?>
When you’re mixing PHP and HTML, this solution solves several problems I had with the previous example. Five lines shorter, all three lines of PHP code share the same indentation level, which also means it’s easy to keep HTML indentation separate so they’re not visually conflicting.
I’ve been playing with this solution in some current projects and it really has worked well so far. Even the designer on these projects is happy to see such a clean alternative.
No related posts.