Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I iterate through two loops of equal size with foreach? [duplicate]

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?

like image 451
Adam Avatar asked Apr 12 '11 21:04

Adam


3 Answers

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
}
like image 84
KingCrunch Avatar answered Oct 19 '22 05:10

KingCrunch


Each returns an array containing the key and value, and advances the pointer to the next element. It returns false once it has advanced past the last element.

// Iterate until one of the arrays is complete
while (($a = each($array_a)) !== false && ($b = each($array_b)) !== false) {
    echo "The key:value from array_a is {$a['key']}:{$a['value']}.\n";
    echo "The key:value from array_b is {$b['key']}:{$b['value']}.\n";
}

To iterate completely over both arrays, use || instead of &&.

like image 43
beefsack Avatar answered Oct 19 '22 04:10

beefsack


use a for loop instead...

for($i = 0;$i<count($array1);$i++) { 
    /* access $array1[$i] and $array2[$i] here */ 
}

This will work if the indexes of the arrays are numeric and the same for both arrays

like image 36
Devin Crossman Avatar answered Oct 19 '22 05:10

Devin Crossman