cbk38
cbk38

Reputation: 23

How to use 2 arrays in a foreach loop PHP for choosing random element

I have two arrays:

$array1 = array("red", "blue", "green", "yellow");
$array2 = array("one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten");

I want to randomly echo 10 times a color.

I tried to do it using foreach loop and shuffle, but when I try this I am getting the error:

Array to string conversion.....

This is my code:

shuffle($array1);
foreach($array2 as $array2) {
    echo $array1;
}

Please can someone help me solving this problem?

Upvotes: 0

Views: 181

Answers (2)

u_mulder
u_mulder

Reputation: 54831

while-variation of another answer:

$i = 0;
while ($i++ < 10) {
    echo $array1[array_rand($array1)];
}

Upvotes: 1

dWinder
dWinder

Reputation: 11642

You messing between array variable and their element.

First, you cannot do echo $array1; as the variable is array and echo is for string. Second, foreach($array2 as $array2) is reassign $array2 as both element so the original array is mess-up.

Better way to do that will be with array_rand:

foreach(range(1,10) as $v) {
    echo $array1[array_rand($array1)] . PHP_EOL;
}

Upvotes: 5

Related Questions