How can I iterate through two arrays at the same time without re-iterating through the parent loop?

php

Solution

Use a normal `for` loop instead of a `foreach`, so that you get an explicit loop counter:

for($i=0; $i<count($content)-1; $i++) {
  echo $content[$i].'-'.$contentb[$i];
}

If you want to use string based indexed arrays, and know that the string indexes are equal between arrays, you can stick with the `foreach` construct

foreach($content as $key=>$item) {
  echo $item.'-'.$contentb[$key];
}

Problem

How can I iterate through two arrays at the same time that have equal sizes ? for example , first array `$a = array( 1,2,3,4,5);` second array `$b = array(1,2,3,4,5);` The result that I would like through iterating through both is having the looping process going through the same values to produce a result like ``` 1-1 2-2 3-3 4-4 5-5 ``` I tried to do it this way below but it didn't work , it keeps going through the first loop again ``` foreach($a as $content) { foreach($b as $contentb){ echo $a."-".$b."<br />"; } } ```

Original source

Related problems