Question

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

Was it helpful?

Solution

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.

OTHER TIPS

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) {
...
...
}

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.

You can read about it in Alternative syntax for control structures in the PHP manual. Reformatted, the code you posted looks like this:

if (preg_match('/foo.*bar/','foo is a bar')):
    echo 'success ';
    echo 'foo comes before bar';
endif;

This code is equivalent to:

if (preg_match('/foo.*bar/','foo is a bar')) {
    echo 'success ';
    echo 'foo comes before bar';
}

This syntax is available for several other control structures as well.

if ( condition ):
  // your if code
elseif ( other_condition ):
  // optional elseif code
else:
  // optional else code
endif;

while ( condition ):
  // your while code
endwhile;

for ( condition ):
  // your for code
endfor;

foreach ( condition ):
  // your foreach code
endforeach;

switch ( condition ):
  // your switch code
endswitch;

It's the equivalent of:

if(preg_match('/foo.*bar/','foo is a bar')):
 echo 'success ';
 echo 'foo comes before bar';
endif;

which is equivalent to:

if(preg_match('/foo.*bar/','foo is a bar')){
    echo 'success ';
    echo 'foo comes before bar';
}

The wisdom of supporting non-standard conditional syntax is obviously questionable.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top