PHP, "Foreach" using 3 arrays

Possible duplicate:
foreach with the addition of three variables

If I have 3 arrays of the same size, can costruct foreach () be used to loop 3 arrays?

ex.

$name contains names $surname contains surnames $address contains addresses. 

You can select the elements [1], [2], [.....] at any time to print

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

etc.?

+4
source share
5 answers

SPL multipleIterator is designed specifically for 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; } 
+17
source

Assuming they are the same length:

 for ($i = 0; $i < count($names); $i++) { echo "{$names[$i]}, {$surnames[$i]}, {$addresses[$i]}"; } 
+6
source

You can do it like this (if arrays have the same keys):

 foreach ($name as $key => $value) { //use $name[$key], $surname[$key], $address[$key] } 

$key contains the key in the $name array

$value = $name[$key]

+4
source

try it

 foreach($arr1 as $i => $val) { var_dump($val, $arr2[$i], $arr3[$i]); } 
+1
source

If the keys of the array are the same, you can use the key() function.

But you can pass the key foreach($array as $key => value()){} This way you can refer to the variable key without using a function.

0
source

All Articles