Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you combine two foreach loops into one

Tags:

foreach

php

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.

like image 823
Kirk Avatar asked Mar 31 '10 22:03

Kirk


2 Answers

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
like image 79
VolkerK Avatar answered Oct 05 '22 23:10

VolkerK


1) First method

<?php
$FirstArray = array('a', 'b', 'c', 'd');
$SecondArray = array('1', '2', '3', '4');

foreach(array_combine($FirstArray, $SecondArray) as $f => $n) {
    echo $f.$n;
    echo "<br/>";
}
?>

or 2) Second method

<?php
$FirstArray = array('a', 'b', 'c', 'd');
$SecondArray = array('1', '2', '3', '4');

for ($index = 0 ; $index < count($FirstArray); $index ++) {
  echo $FirstArray[$index] . $SecondArray[$index];
  echo "<br/>";
}
?>
like image 21
T.Todua Avatar answered Oct 06 '22 00:10

T.Todua