14

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 />"; 
    }
}
Rogers
  • 2,905
  • 3
  • 14
  • 11
  • 1
    Are these arrays indexed the same way? Then just iterate over the index... `for ($ii=...)` – Floris Mar 18 '13 at 21:38
  • possible duplicate: [php looping through multiple arrays](http://stackoverflow.com/q/9171488/367456) – hakre Jun 23 '13 at 11:58

3 Answers3

24

Not the most efficient, but a demonstration of SPL's multipleIterator

$mi = new MultipleIterator();
$mi->attachIterator(new ArrayIterator($a));
$mi->attachIterator(new ArrayIterator($b));

$newArray = array();
foreach ( $mi as $value ) {
    list($value1, $value2) = $value;
    echo $value1 , '-' , $value2 , PHP_EOL;
}
Mark Baker
  • 209,507
  • 32
  • 346
  • 385
19

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];
}
Nick Andriopoulos
  • 10,313
  • 6
  • 32
  • 56
4

If they're the same size, just do this:

foreach($a as $key => $content){
   $contentb = $b[$key];
   echo($content."-".$contentb."<br />");
}
HamZa
  • 14,671
  • 11
  • 54
  • 75
LuaWeaver
  • 316
  • 2
  • 8