Emily
Emily

Reputation: 915

How to bind arrays?

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

Upvotes: 1

Views: 155

Answers (2)

Prine
Prine

Reputation: 12538

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 

Upvotes: 3

VolkerK
VolkerK

Reputation: 96159

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

Upvotes: 8

Related Questions