Is there a way to do a foreach with two variables at the same time?

13

I tried to separate by comma, but it did not work:

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

I know there are other ways to make this foreach work, but I wanted to get this curious. Is it possible to use two variables in a foreach using PHP?

    
asked by anonymous 19.01.2016 / 13:03

2 answers

11

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

foreach(array_combine($dados, $telefones) as $d => $t)
{
}
    
19.01.2016 / 13:07
2

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

Array_map

Actually, it's not a foreach , but it's 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 output will be:

146
257
368

See an example:

link

Foreach with list

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

See:

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

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

In this case the result would be:

123
456
678
    
21.09.2016 / 17:14