Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to implement a foreach inside a for loop in PHP?

I’m new to PHP & Stackoverflow. Correct my questions if I make a mistake here.
My goal to accomplish here is to get a random color (for loop) followed by the sequence (foreach) accordingly. Here is my code below.

  $color = array("green", "red", "yellow");
  $sequence = array("R", "B", "B");

  for ($x = 1; $x <= 10; $x++) {
    $color_random = $color[array_rand($color)];
    echo $color_random . "- ";
  }

  foreach ($sequence as $sequence_value) {
    echo $sequence_value . "- ";
  }

Currently the results is "yellow- green- yellow- red- green- green- red- green- yellow- green- R- B- B-"
.

How can I convert it/change it to yellow-R- green-B- yellow-B- red-R- green-B- green-B- red-R- green-B- yellow-B- green-R- (random color – sequence -) As you can see, 10 random colors generated, but the sequence follows according.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Any answers or comments would be great as this is learning progress for me and others as well. Thank you.

>Solution :

You can try this:

$color = array("green", "red", "yellow");
$sequence = array("R", "B", "B");

for ($x = 1; $x <= 10; $x++) {
foreach ($sequence as $sequence_value) {
    $color_random = $color[array_rand($color)];
    echo $color_random . "- " . $sequence_value . "- ";
}
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading