I have three colors in an array, array('blue', 'red', 'green'), and in my loop, I want to be able to print blue, red, green, blue, red, green.
I know that I could just reset a counter every 3 loops, and use that to find the color I want – 1, 2, 3, reset, 1, 2, 3, reset, etc. But is there a simple way to pass it the current loop count, like, 5 or 7, and get 2? Or pass 6 or 9 and get 3? Am I missing some simple math solution to this?
What you’re looking for is the modulo operator ‘%’;
basically this means divide the number by 3 and give me the remainder…so it’ll equal 0 1 2 0 1 2 0 1 2, etc…
EDIT:
If you’re using a language that starts array indexes at 1 you can do: