0

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?

2
  • check your idea in correct syntax : eval.in/1111066 Commented Jun 6, 2019 at 8:04
  • cbk38 did length of $array2 can increase or decrease? or it will be always 10? Commented Jun 6, 2019 at 9:19

2 Answers 2

5

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;
}
Sign up to request clarification or add additional context in comments.

Comments

1

while-variation of another answer:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.