Alex Rivera | Logout

How do you combine two foreach loops into one

Asked 2010-03-31T22:43:06.973
9

The language is PHP. I have one foreach ( $a as $b) and another foreach ($c as $d => $e). How do i combine them to read as one. I tired foreach (($a as $b) && ($c as $d => $e)), but that is rubbish.

Edit
Report

2 Answers

26

You might be interested in SPL's MultipleIterator

e.g.

// ArrayIterator is just an example, could be any Iterator.
$a1 = new ArrayIterator(array(1, 2, 3, 4, 5, 6));
$a2 = new ArrayIterator(array(11, 12, 13, 14, 15, 16));

$it = new MultipleIterator;
$it->attachIterator($a1);
$it->attachIterator($a2);

foreach($it as $e) {
  echo $e[0], ' | ', $e[1], "\n";
}

prints

1 | 11
2 | 12
3 | 13
4 | 14
5 | 15
6 | 16
answered 2010-03-31T22:48:11.153
3

I don't understand what you're trying to do. If you want to reach them one after the other just use two loops:

foreach ($a as $b) { ... }
foreach ($c as $d => $e) { ... }

If you want all combinations from $a and $c:

foreach ($a as $b) {
  foreach ($c as $d => $e) {
    // do stuff
  }
}

I guess you could do something like:

foreach (array_merge($a, $c) as $k => $v) {
  ...
}

but I wouldn't necessarily advise it.

answered 2010-03-31T22:47:08.667

Your Answer