Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

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 />"; 
    }
}
like image 611
Rogers Avatar asked Mar 18 '13 21:03

Rogers


1 Answers

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;
}
like image 174
Mark Baker Avatar answered Oct 07 '22 01:10

Mark Baker