views:

158

answers:

6

I have seen in cakephp that foreach loop is used like this


foreach($tags as $tag) :
       \\code here
endforeach;

and I used to write this style of foreach


foreach($tags as $tag)
{
     //code here
}

what is the difference between these two foeach loops and which one is better and makes more sense to implement ?

Thanks

+2  A: 

They are identical. I'd use the ones with the curly braces though, since the syntax is more like other PHP constructs, C, C++, Java, etc..

Brendan Long
I'd say it was dependent on where they were being used. In a file that contains purely php code, then the second, curly braces makes more sense. If implementing light logic in a template or view, the second approach is vastly more readable.
navitronic
+6  A: 

They are equivalent, but the second first is sometimes more readable when your PHP is embedded with HTML.

Greg
I'd say that the first is more readable when used within html. Curly braces from php and html don't go well together IMO.
navitronic
I agree -- that's actually what I intended. :)
Greg
Indeed, the first is commonly used in WordPress templates.
Justin Johnson
Just to clarify, in a CakePHP context, you might decide that views and elements (those with the .ctp extension) use the first form and all other files (ie. classes with .php extensions) use the latter.
deizel
Anyone know the terms for the two different types of syntax?
Travis Leleu
+2  A: 

They are equivalent, but the first one sometimes is more readable when your PHP is embedded in HTML.
:)~

As of it's equality, no method can be called "better", and can be only subject of agreement.

Col. Shrapnel
+2  A: 

The first one dates from an early PHP syntax (before PHP 4) and the second one is what's generally accepted now. IMHO I'd avoid using the first one and would always use curly braces, even for something like

<?php foreach ($foo as $f) { ?>
<div><?= $f ?></div>
<?php } ?>

Because many editors have brace highlighting and it's just better that way :)

Yanick Rochon
I'm afraid you're wrong with dates. PHP before 4 version isn't that ancient ;)
Col. Shrapnel
http://ca2.php.net/manual/en/history.php.phpYou can see there that, before PHP3, there was no such thing as curly braces in the language :) ...about 13 years ago
Yanick Rochon
+2  A: 
Mihai Iorga
A: 

It comes down to personal or team coding standards. I prefer the {} option as it makes more universally readable code. True, it gets messy in HTML, but again with a coding standard you can ease that.

If you have a lot of HTML and PHP within the loop, using the : option can create serious confusion lower down in the code, especially if the loop runs off the bottom of the page. Syntax highlighting with {} will let you identify the loop contents much more easily.

Leo