Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP, "Foreach" using 3 arrays [duplicate]

Possible Duplicate:
foreach with three variables add

If I have 3 arrays of the same size, is it possible to use the costruct foreach() to cycle in the same time the 3 arrays?

ex.

$name contains names

$surname contains surnames

$address contains addresses.

Can foreach take elements [1], [2], [.....] in the same time, to print

$name[1], $surname[1], $address[1];

$name[2], $surname[2], $address[2];

and so on?

like image 813
user1722791 Avatar asked Dec 28 '12 14:12

user1722791


1 Answers

SPL's multipleIterator is designed for precisely this purpose

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

foreach ( $mi as $value ) {
    list($name, $surname, $address) = $value;
    echo $name , ' => ' , $surname , ' => ' , $address , PHP_EOL;
}
like image 60
Mark Baker Avatar answered Oct 04 '22 02:10

Mark Baker