8

As seen in this other answer, there are several ways to iterate two same-sized arrays simultaneously; however, all of the methods have a rather significant pitfall. Here are some of the caveats with the methods suggested:

  • You can't use FALSE values in one of the arrays.
  • You can only use scalar values in one of the arrays.
  • You must use numerically indexed arrays.
  • Both arrays must share the same keys.
  • Etc.

My question is - is there a method for doing this which doesn't suffer from any of these (or other) significant caveats?

Bear in mind that I'm simply asking this out of curiosity; I have no use-case in mind, nor do I even know if such a case actually exists or would be useful/practical in a real-world scenario. However, here is some example data:

$arr1 = [ 'a' => 1, 'b' => FALSE, 'c' => new DateTime() ];
$arr2 = [ 'foo', TRUE, 7 ];
Community
  • 1
  • 1
FtDRbwLXw6
  • 27,774
  • 13
  • 70
  • 107
  • What's wrong with beefsack's answer to that question? Seems like it would work regardless of the content or structure of the arrays. – nickb Apr 12 '12 at 21:44
  • it would not work with because `'b' => FALSE` @nickb – Baba Apr 12 '12 at 21:53
  • @Baba - No, [it works with `'b' => false`](http://codepad.viper-7.com/nNZuNj). – nickb Apr 13 '12 at 13:10

3 Answers3

24

You can use a MultipleIterator:

$iterator = new MultipleIterator;
$iterator->attachIterator(new ArrayIterator($array1));
$iterator->attachIterator(new ArrayIterator($array2));

foreach ($iterator as $values) {
    var_dump($values[0], $values[1]);
}

You can find more examples concerning the various options in the docs.

NikiC
  • 100,734
  • 37
  • 191
  • 225
4

As of PHP 5.5 you can do this:

foreach (array_map(null, $array1, $array2) as list($item1, $item2))
{
    var_dump($item1);
    var_dump($item2);
}

http://us3.php.net/manual/en/control-structures.foreach.php#control-structures.foreach.list

Hans
  • 2,230
  • 23
  • 23
1
<?php

$arr1 = array( 'a' => 1, 'b' => FALSE, 'c' => new DateTime() );
$arr2 = array( 'foo', TRUE, 7, 5 );


reset($arr1);
reset($arr2);    

while ( (list($key, $val) = each($arr1))
    && (list($key2, $val2) = each($arr2))
) {
    var_dump($val,$val2);
    // or whatever you wanted to do with them
}

http://www.php.net/manual/en/function.each.php

craniumonempty
  • 3,525
  • 2
  • 20
  • 18
  • 1
    your script has error and would not work if total arrays in `$arr2` > `$arr1` ... correct it before they start voting you down – Baba Apr 12 '12 at 21:59
  • @Baba I had find a server to test, because I didn't really test it the first go. It wasn't a problem with the length of the arrays (from what I could tell), but there were problems (like I don't have 5.4 on the server I tested on), so thanks for pointing that out. – craniumonempty Apr 12 '12 at 22:16