What is the difference between foreach uses in php?

Asked

Viewed 894 times

5

What is the difference between these two means of using the foreach in php? One would be more special than the other, bringing some advantage for example?

Method 1:

foreach ($arr as $key => $value) {
    #do something 
}

Method 2:

foreach ($arr as $key => $value): 
  #do something 
endforeach;

There are other variations like this for the foreach or for other similar instructions in php?

  • 1

    personally I use it like this: when the block is small enough to see beginning and end on the same screen or when there are not many blocks inside each other, I use {}. When the block is long enough for you to have to scroll the screen, when there is much HTML in the middle or when there are so many if/Else/foreach/for/while together that is that huge ass of } in the end I prefer endif; endforeach; etc, because it is easy to see where each one ends.

  • Following this logic I also know that if I’m being too much using the second option is because there’s probably a smarter/shorter way to do what I want and I need to refactor. My future self always thanks you when you have to go back there.

  • related http://answall.com/questions/25184/n%C3%A3o-usar-chaves-em-if-no-php-pode-gerar-problemas

3 answers

8

I had seen this before, but I searched it just to confirm. There’s no difference, technically speaking.

The second method is most used when there are html codes in the medium, for example:

<?php
    $arr = blah();
    foreach ($arr as $key => $value):
?>
<h1>Hello .. <?php echo $value; ?></h1>
mais código html aqui...
<?php endforeach; ?>

It looks more elegant than that:

<?php
    $arr = blah();
    foreach ($arr as $key => $value) {
?>
<h1>Hello .. <?php echo $value; ?></h1>
mais código html aqui...
<?php } ?>

There are several others.. if/endif; switch/endswitch; for/endfor. You can check the list in the php manual

7

There is no difference in terms of functioning, internally both will become the same when executed.

Its raison d'être is merely an option, it seems, for better legibility in different contexts. There are situations where the indentation gets confusing, especially when mixed with HTML blocks, as already said by colleague @Kirito94, but this can only be analyzed case by case.

As the PHP manual itself says:

PHP offers an alternative syntax for some control structures; namely, if, while, for, foreach, and switch. In each case, basically the alternative syntax is to exchange the opening key for two points (:) and the closing key for endif;, endwhile;, endfor;, endforeach;, or endswitch;, respectively.

Still, in the manual, it is clear that works in the blocks of else and elseif

<?php
if ($a == 5):
    echo "a equals 5";
    echo "...";
elseif ($a == 6):
    echo "a equals 6";
    echo "!!!";
else:
    echo "a is neither 5 nor 6";
endif;
?>

More details on the link:

Alternative syntax for control structures.

  • For the record, I always use { and }, Depending on your degree of organization, it does not hinder readability in anything. Even, the way I use it, it would be more confusing with closure "in full". You need to see the context of each, I do not believe that in this case there is a possible rule to determine which one is best. It only depends on the style of each.

  • Thanks for quoting the documentation, I hadn’t seen much use of it to know that it wasn’t just used with the foreach .

  • 1

    @Florida I understand, is that when you see for the first time in a real code, it gives the impression that it is the same foreach thing. I just put the comment in your question before answering to advance the subject while formatting the answer.

2


Complementing the existing responses and to avoid talking more of it, within this context also enters the code patterns.

Standards widely accepted by PHP communities worldwide.
*It does not mean that everyone accepts. Some refute or ignore.

An example is the patterns of http://www.php-fig.org/

We can mention the PSR-2.

Everything that is "alternative syntax" or "aliases" is always outside the code patterns. In the case of PSR-2, the default always proposes to use keys {} for opening and closing flow control structures and declaration of functions and classes.

Example

class Foo
{

}

There are certain detailed rules, as an example, this is considered "wrong"

class Foo 
{

}

Visually looks the same as the first, but note that there is a space before breaking the opening of {. Ides in restricted mode may issue a correction warning.

For PHP, it is indifferent:

class Foo {

}

class Foo{}

The issue is more visual and optimization for Ides and third-party compilers and obviously organization/standardization of writing.

There was a time when many omitted the cholchetes in 1-line instructions and even was widely diffused and became standard in many documentations:

if(instrução)
    //faz isso

//outro código

Another way

if(instrução)
    //faz isso
else
    //faz aquilo

Currently the recommendation is to avoid deleting the brackets as it can bring confusion. ON PSR-2, ask for even when there is only 1 line, always write the square bracket.

if (instrução) {
    //faz isso
} else {
    //faz aquilo
}

Note also that there are details in this last example:
- Just after the if there is a space.
- No spaces in parentheses.
- Just after closing the parenthesis there is a space

It is important to maintain this standard as many platforms adopt the PSR-2 and validate codes within these standards. You may have trouble adapting hundreds of thousands of codes by following another unknown pattern or by inventing one that is not the same as PSR.

There are certain tolerances for alternative syntaxes such as the use of this syntax

echo (condição)? 'ok': 'ng';

Here I mentioned the if, but the same applies to other flow control structures

foreach () {

}

while () {

}

for () {

}

Note that the above examples are based on PSR rules. Code pattern standards may vary depending on the platform you use.

An example, Wordpress allows something like this if ( condition ) {

This space in the condition is not allowed other platforms that do not tolerate it, such as the Prestashop syntax validator, for example.

But Wordpress allows you to write this way if (condition) {.

Therefore, it is always best to follow what is most widely accepted because a code you write for a platform can be accepted more easily on a third platform.

An example using Prestashop itself, this platform, until 2 years ago, required the deletion of keys in a row instructions:

if ()
    //uma linha

However, they recently changed this pattern. It is currently not allowed. Those who used the PSR-2 standard did well because they had no trouble changing anything. Prestashop has adopted the PSR-2 and requires its use.

The same can happen with other platforms like Wordpress, Magento, etc.

*I cited these platforms as being popular.

Still there are those who refuse to use the php-fig.org defaults. As for this we can not do anything because this site is totally independent of PHP and is not a kind of law where everyone is required to follow.

However, one fact that no one can deny is that these PHP-fig patterns are widely accepted worldwide. You can be in Afghanistan, Mexico, Brazil, Vietnam or Greenland and you will find PHP programmers following this pattern. It’s not something located where people from one country follow and the rest of the world doesn’t know.

Here I avoided commenting on patterns of indentation and line breaking in long conditionals because the focus of the question is specific on the use of alternative syntax keys {}.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.