Foreach followed by another Foreach on the same line

Asked

Viewed 66 times

2

It is correct to use a foreach followed by another foreach (as in the example below)?

<?php if($nome1):

    foreach ($nome1 as $nome2) foreach ($nome2->nome3() as $nome4):
?>

#code html

<?php

    endforeach;

else:

?> etc...
  • Thus, you can use a foreach inside another foreach, as you posted in your code I do not see how it can work. I believe it would have to be like this: foreach($array_1 as $val){ foreach($array_2 as $val) { } }

  • Hello Edward. Believe it, it works! Even breaking the line and throwing one Foreach down the other. I just don’t know if it’s right to use it that way because I care about good practice.

  • The law of PHP says: If it worked, it just will! kkkkkkkkkkkkkkkk

  • I don’t know if you’re right about this syntax. You should use {}.

1 answer

0


It is possible, the syntax is valid, there is no correct or wrong one, so you can use if that’s what you want to do.

Just like in C, in PHP it is possible to omit keys when defining a logical block, both in conditional and repetition loops.

For example, in

if (condition) {
    a;
    b;
}

Both the expressions a how much b are in the logical block of the conditional and will be evaluated only when the condition is true.

Already in

if (condition)
    a;
    b;

Just the expression a is part of the logical block, while b no; this implies that b will be assessed independently of the condition - and could be rewritten, to facilitate understanding, as:

if (condition)
    a;
b;

The same goes for the foreach. When you omit the keys, only the first expression after the instruction will be part of the logical block. By lucky, another foreach is considered as an expression only until the occurrence of endforeach or the keys, if.

Therefore, do:

foreach ($nome1 as $nome2) foreach ($nome2->nome3() as $nome4):

It’s the equivalent of doing:

foreach ($nome1 as $nome2)
    foreach ($nome2->nome3() as $nome4):
        ...
    endforeach;

Which is the same as:

foreach ($nome1 as $nome2) {
    foreach ($nome2->nome3() as $nome4) {
        ...
    }
}

If that’s what you need, then yes, that’s correct.

Browser other questions tagged

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