Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strange PHP syntax

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 :)

like image 975
Joseph Avatar asked May 07 '10 13:05

Joseph


3 Answers

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) {
...
...
}
like image 126
codaddict Avatar answered Nov 03 '22 10:11

codaddict


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.

like image 43
Harold1983- Avatar answered Nov 03 '22 10:11

Harold1983-


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.

like image 41
binaryLV Avatar answered Nov 03 '22 10:11

binaryLV