tags:

views:

48

answers:

2

Say i have those 3 arrays :

Product(milk,candy,chocolate)
Colors(white,red,black)
Rating(8,7,9)

How to create a loop to bind those arrays so i get 3 variables in each loop : $product $color $rating

So by example i will output like this:

Milk is white and has a rating of 8/10

Candy is red and has a rating of 7/10

Chocolate is black and has a rating of 9/10

Thanks

+8  A: 

E.g. by using SPL's MultipleIterator

<?php
$Product=array('milk','candy','chocolate');
$Colors=array('white','red','black');
$Rating=array(8,7,9);

$it = new MultipleIterator;
$it->attachIterator(new ArrayIterator($Product));
$it->attachIterator(new ArrayIterator($Colors));
$it->attachIterator(new ArrayIterator($Rating));

foreach( $it as $e ) {
  echo join(' - ', $e), "\n";
}

prints

milk - white - 8
candy - red - 7
chocolate - black - 9
VolkerK
That's very tidy, I like it.
Justin Johnson
Wow, never heard of MultipleIterator, I need to study the SPL library more, thanks!
WishCow
+3  A: 

I dont know if I get it right. But do you want something like this?

$products = array("milk", "candy", "chocolate");
$colors = array("white", "red", "black");
$ratings = array(8, 7, 9);

 for($i = 0; $i < sizeof($products); $i++) {
    $product = $products[$i];
    $color = $colors[$i];
    $rating = $ratings[$i];

    echo $product . ' is ' . $color . ' and has a rating of ' . $rating . '/10 <br/>';
 }

Output would be:

milk is white and has the rating of 8/10
candy is red and has the rating of 7/10
chocolate is black and has the rating of 9/10 
Prine