1

Here is my code:

$bag3 = 7; $row = 4; $nom = 1; $arr = array("red", "green", "blue", "yellow"); while ($bag3){ while ($nom <= $bag3){ echo $ay." ".$row; $nom++; $row++; }if ($nom == $bag3){ $nom = 1; } } 

and here's the output:

red 4red 5red 6red 7red 8red 9red 10 

I want it to loop through all the array values: red, green, blue, and yellow. like this:

red 4red 5red 6red 7red 8red 9red 10green 11green 12green 13green 14green 15green 16green 17blue 18blue 19blue 20blue 21blue 22blue 23blue 24yellow 25yellow 26yellow 27yellow 28yellow 29yellow 30yellow 31 

What should I change in my code?

1 Answer 1

4

You can simplify your code with a foreach loop over the array and a for loop for $nom from 1 to $bag3:

$bag3 = 7; $row = 4; $arr = array("red", "green", "blue", "yellow"); foreach ($arr as $ay) { for ($nom = 1; $nom <= $bag3; $nom++, $row++){ echo $ay." ".$row; } } 

Output:

red 4red 5red 6red 7red 8red 9red 10green 11green 12green 13green 14green 15green 16green 17blue 18blue 19blue 20blue 21blue 22blue 23blue 24yellow 25yellow 26yellow 27yellow 28yellow 29yellow 30yellow 31 

Demo on 3v4l.org

Sign up to request clarification or add additional context in comments.

2 Comments

That is one wicked/tricky looping there Nick. I'm curious though, does it always end on an integer but no repeating text after? As you might have noticed, arrays and me don't make best of friends.
@FunkFortyNiner it's probably more clear with newlines in the output (3v4l.org/EBaud), but yeah, it will always finish with a $row value which is going to be an integer.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.