Wednesday, March 25, 2009

PHP alternative control structure syntax

PHP offers an alternative syntax for most of its control structures that is handy for enhancing the readability of PHP code embedded within html. For the control structures if, while, for, foreach, and switch simply replace the opening bracket ({) with a colon (:) and end the statement with endif, endwhile, endfor, endforeach, and endswitch respectively. For instance, here's some embedded PHP code using the standard control structure syntax:
<?php if ($showthis) { ?>

<p>some html stuff here</p>
<i>blah</i>

<?php } else { ?>

<p>some other stuff</p>
<i>fubar</i>

<?php } ?>

And using the alternative syntax this becomes:
<?php if ($showthis): ?>

<p>some html stuff here</p>
<i>blah</i>

<?php else: ?>

<p>some other stuff</p>
<i>fubar</i>

<?php endif; ?>

With the alternative syntax it is easier to see where one block ends and another begins, and separates out the code from the content in a way that is more readable. This is especially true for situations where you have multiple nested loops and control statements.

No comments:

Post a Comment