tags:

views:

75

answers:

4

Hi. In an effort to produce cleaner PHP files, I want to echo less HTML and embed more PHP. I've stumbled upon constructs like the following:

<?php
foreach($allOGroups as $ogroup):
if($lastGroup != $ogroup['group']):
if($lastGroup !== null):
?>

</optgroup>

<?php
endif;
?>

I've googled for a while now but can't seem to find a tutorial on how to use this mysterious ":" operator. Can anyone point me in the right direction?

Thanks, MrB

+2  A: 

Alternative syntax for control structures:

if ($a == $b) {
    echo $a;
}

// is same as:
if ($a == $b):
    echo $a;
endif;

This syntax was introduced to make embedding PHP in HTML easier. By telling which block to close the code becomes more understandable.

nikic
A: 

It's a feature of PHP's conditional constructs. Instead of using braces to punctuate the block, you use : and the corresponding keyword.

Also, it has nothing to do with embedding PHP or HTML.

Ignacio Vazquez-Abrams
imho it has everything to do with embedding PHP in HTML. That's the main purpose of this alternative syntax.
nikic
+1  A: 

As you have discovered, the mysterious : is simply an alternative syntax to opening and closing curly brackets. It's most effective when you're mingling PHP with HTML, since it makes it easier to discover whether you're closing an if, for, foreach or while structure.

if($foo):
  // Do something
endif;

for($i = 0; $i < 10; $i++):
  // Do something
endfor;

foreach($foo as $k, $v){
  // Do something
endforeach;

while($foo):
  // Do something
endwhile;
Johannes Gorset
Thanks you guys for clearing that up!
MrBubbles
A: 

: isn't an operator, it's simply part of an alternative syntax for control structures. Personally, I wouldn't use it. There's no benefit over using 'standard' syntax, and I think it's marginally harder to read.

Mark Baker
There's plenty of benefit to using it over curly brackets if you're mingling PHP with sizeable sections of HTML.
Johannes Gorset
FRKT - In terms of benefit, I was referring to performance, memory usage, etc. As far as I'm aware, it's no faster to execute, and doesn't reduce the size of bytecode in any way. In terms of readability, which seems to be the most common feature that some people see as a benefit, I expressed a personal opinion that I consider it less readable than more... especially when using nested constructs.
Mark Baker