简体   繁体   English

这两个foreach循环有什么区别?

[英]what is the difference between these two foreach loops?

I have seen in cakephp that foreach loop is used like this 我在cakephp中看到foreach循环是这样使用的


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

and I used to write this style of foreach 我曾经写过这种风格的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 ? 这两个foeach循环之间有什么区别,哪个更好,实现起来更有意义?

Thanks 谢谢

它们是等效的,但是当您的PHP嵌入HTML时, 第二个 有时更具可读性。

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.. 我会使用花括号,因为语法更像其他PHP结构,C,C ++,Java等。

They are equivalent, but the first one sometimes is more readable when your PHP is embedded in HTML. 它们是等效的,但是当您的PHP嵌入HTML时,第一个有时更具可读性。
:)~ :)〜

As of it's equality, no method can be called "better", and can be only subject of agreement. 就其平等性而言,没有一种方法可以被称为“更好”,并且只能是达成协议的对象。

The first one dates from an early PHP syntax (before PHP 4) and the second one is what's generally accepted now. 第一个可以追溯到早期的PHP语法(在PHP 4之前),而第二个则是目前普遍接受的语法。 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 :) 因为许多编辑器都用大括号突出显示,这样更好:)

They are completely identical, thus the first one is most likely to be used because it allows one to let the braces go, you don't need to remember where the braces are and what is open when adding a large part of other codes or HTML design. 它们是完全相同的,因此最有可能使用第一个,因为它允许将括号放开,在添加大量其他代码或HTML时,您无需记住括号在哪里以及打开的内容设计。

Just like the alternative for IF statement: 就像IF语句的替代方法一样:

<?php
if ($foo):
   echo "is ok\n";
elseif ($bar):
   echo "not ok\n";
else:
   echo "dont't know\n";
endif;
?>

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. 没错,它在HTML中变得凌乱,但再次使用编码标准,您可以缓解这种情况。

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. 如果循环中包含大量HTML和PHP,则使用:选项会在代码的下方产生严重的混乱,尤其是当循环从页面底部开始时。 Syntax highlighting with {} will let you identify the loop contents much more easily. 用{}突出显示语法将使您更轻松地识别循环内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM