Can I iterate through two loops of equal size with foreach?
for-loop, foreach, php
Solution
while (($element1 = next($array1)) !== false) {
$element2 = next($array2);
// Do something
}
But it will fail, if `false` is an allowed value in `$array1`. If (in this case) `false` is not allowed in `$array2`, you can just swap both
A "foreach"-solution (if both shares the same key)
foreach ($array1 as $i => $element1) {
$element2 = $array2[$i];
// Do something
}
A third (I think quite nice) solution, that just allows primitive types in `$array1`
foreach (array_combine(array_values($array1), array_values($array2)) as $element1 => $element2) {
// Do something
}
Problem
I'm new to PHP. I have two arrays `$array1` and `$array2` of equal size. I've been using `foreach` loops to iterate through arrays like so: ``` foreach($array1 as $element1) { //Do stuff with $element1 } ``` and ``` foreach($array2 as $element2) { //Do stuff with $element2 } ``` but now I'd like to iterate through both arrays at the same time so that I have access to both `$element1` and `$element2` in the loop body. How do I do that?