Is there any way to foreach two variables at once?

Asked

Viewed 4,492 times

14

I tried separating by comma, but it didn’t work:

foreach($dados as $d, $telefones as $t){}

I know there are other ways to do this foreach that work, but I wanted to remove this curiosity. It is possible to use two variables in a foreach using PHP?

  • what relationship exists between $dados and $telefones ?

  • Both have a common identifier. Exists $dados->ra and $telefones->ra

  • Related : http://stackoverflow.com/questions/4480803/two-arrays-in-foreach-loop

2 answers

13


If it is two arrays, can be done as follows:

foreach(array_combine($dados, $telefones) as $d => $t)
{
}

3

I know the question has already been answered, but I believe that the current answer only meets the cases where the first array contains only numbers or string. If you have a Object or Array, array_combine will fail.

Array_map

Actually, it’s not a foreach, but it is a loop with as many arrays as you want at the same time!

My solution to this is with array_map.

See the magic:

$a = [1, 2, 3];

$b = [4, 5, 6];

$c = [6, 7, 8];



array_map(function ($v1, $v2, $v3) {
    echo $v1, $v2, $v3, PHP_EOL;

}, $a, $b, $c);

The exit will be:

146
257
368

Take an example:

https://ideone.com/aSEM9i

Foreach with list

In addition to the example already mentioned, I would also like to demonstrate here that PHP, from version 5.5, has a new feature: Use list in the foreach.

Behold:

foreach ([$a, $b, $c] as list ($value1, $value2, $value3)) {

        echo $value1, $value2, $value3, PHP_EOL;
}

Then the result would be:

123
456
678

Browser other questions tagged

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