1

Ok, so I have two arrays – one for posts, and a limited array of 5 values for the colors to give each post. What I want is for the posts to cycle through the array of colors, so that every 6th starts over. What I'm doing now works per se with a limited number of posts, but it's kind of hacky not very elegant:

$colors = array('yellow', 'red', 'blue', 'green', 'purple');

foreach($posts as $i => $post) {
  $color = $colors[$i];
  if ($i >= count($colors)) {
    $color = $colors[-count($colors) + $i];
    if ($i >= (count($colors) * 2)) {
      $color = $colors[(-count($colors) * 2) + $i];
    }
  }
//Do stuff here
}

I'm sure there's a smarter way to do this, I just don't know how.

1 Answer 1

2

The modulus 5 (%5) will do the quick fix

for($i=0;$i<count($posts);$i++){
   $color=$colors[$i%5];
   # todo here
}
Sign up to request clarification or add additional context in comments.

4 Comments

and then count($colors) instead of 5
That's awesome!
@ruud that is making the program heavier, we already know the number
ok, but if the color array is changed, then the number must also be changed. Better to have a program that always works then to have a lighter program that is vulnerable to this kind of bugs.

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.