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
what relationship exists between
$dados
and$telefones
?– WeezHard
Both have a common identifier. Exists
$dados->ra
and$telefones->ra
– Amanda Lima
Related : http://stackoverflow.com/questions/4480803/two-arrays-in-foreach-loop
– Guilherme Lautert