A simple PHP if
/ else
condition looks like this:
if(true) {
echo("Hello World!");
} else {
echo("Goodbye World!");
}
The "alternative syntax" looks like this:
if(true):
echo("Hello World!");
else:
echo("Goodbye World!");
endif;
I have a few questions regarding this "alternative syntax":
- When / in what case should I use it?
- Where / in which part of my script should I use it?
- Why should I use it / what purpose does it serve & are there any benefits to using it?
- Why was it created, does the "alternative syntax" have features that "original syntax" doesn't?
Thank you for you time & help in advance.
I typically only use it when mixing HTML and PHP, so just for the sake of argument, here is an example to compare
<?php foreach( $vars as $var ): ?>
<?php if($var):?>
<p>Hello World!</p>
<?php else:?>
<p>Goodbye World!</p>
<?php endif;?>
<?php endforeach; ?>
<?php foreach( $vars as $var ){ ?>
<?php if($var){ ?>
<p>Hello World!</p>
<?php }else{ ?>
<p>Goodbye World!</p>
<?php } ?>
<?php } ?>
Granted this is small but if you extend this out about 800 lines it can get tricky to keep track of all those }
having the endif;
endforeach
etc.. gives you just a bit better way to match the code blocks up when mixed with all the HTML content.
Again, I rarely use mixed HTML/PHP and I'd suggest using a Template engine if you have more then a few lines to do that mix the two. Because even this can wind up messy once you have a dozen endif;
it loses it's point.
But, I guess in short I tend to think of it as a default template syntax...