| PHP IF-statements around HTML | |
Code added since previous step is in blue.
Comments are in (you can remove those from your code if you want).
If you're new to PHP or come from ASP like myself, you might notice you can't start an IF-statement, close the PHP, enter HTML, open the PHP and end the IF-statement. Or can you?
Let's first look at why you'd want to even do that:
- editing PHP content in WYSIWYG editors (like Adobe Dreamweaver) is great, as long as you stick with the Code view.
- editing HTML surrounded by PHP is easy in Design view (unless you use includes).
- editing HTML surrounded by PHP is easier in Code view as you don't have to worry about escaping quotes (\") and the likes.
In ASP you can do this:
<% if CONDITION then %>
<% else %>
<% end if %>
If you'd try to do that in PHP, you'd probably do this:
<?php
if (condition) { ?>
<?php
} else { ?>
}
?>
I tried that, and didn't get it working, so I searched, searched and searched some more until I found out you're supposed to do it like this:
<?php if (CONDITION) : ?>
<?php else : ?>
<?php endif; ?>
To make an IF-ElseIf-Else-statement, you do this:
<?php if (CONDITION) : ?>
<?php elseif : ?>
<?php else : ?>
<?php endif; ?>
And that's all there is to it.
Just replace the left curly bracket ({) with a colon, forget about the right curly bracket (}) until you're at the very end of the statement, where you put endif; (with the semi-colon!) to close it.
Side note: you can (should?) use this type of IF-statement at any time, even in an all-PHP file, so don't think this is limited to use only when you're working around HTML codes.
Need more explanation? Found a typo? Contact me. |
|