I've been working on PHP for some time but today when I saw this it came as new to me:
if(preg_match('/foo.*bar/','foo is a bar')):
echo 'success ';
echo 'foo comes before bar';
endif;
To my surprise it also runs without error. Can anyone enlighten me?
Thanks to all :)
This is PHP's Alternative syntax for control structures.
Your snippet is equivalent to:
if(preg_match('/foo.*bar/','foo is a bar')) {
echo 'success ';
echo 'foo comes before bar';
}
In general:
if(cond):
...
...
endif;
is same as
if(cond) {
...
...
}
That style of syntax is more commonly used when embedding in HTML, especially for template/display logic. When embedded this way, it's a little easier to read than the curly braces syntax.
<div>
<? if ($condition): ?>
<ul>
<? foreach($foo as $bar): ?>
<li><?= $bar ?></li>
<? endforeach ?>
</ul>
<? endif ?>
</div>
Versus:
<div>
<? if ($condition) { ?>
<ul>
<? foreach($foo as $bar) { ?>
<li><?= $bar ?></li>
<? } ?>
</ul>
<? } ?>
The verbose end tags make it a little easier to keep track of nested code blocks, although it's still mostly personal preference.
http://php.net/manual/en/control-structures.alternative-syntax.php
Works for if, for, while, foreach, and switch. Can be quite handy for mixing PHP and HTML.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With