user2432283
user2432283

Reputation: 3

Return to the beginning of an array during a foreach loop in PHP (Cyclic)?

When you reach the end of an array in a PHP foreach loop, is there anyway to just start from the beginning again?

I'm building a graph using JS and PHP of a group of different people. I would like to have a different colour for each person on the graph but the number of people varies and is unknown.

I've built an array of hex codes to loop through but the problem is that when the number of people exceeds the number of hex codes in the array an error is thrown.

I realised I could just copy and paste the hex codes until there are more than the number of people but it doesn't seem like a very elegant solution.

Any thoughts?

Upvotes: 0

Views: 803

Answers (3)

markdwhite
markdwhite

Reputation: 2449

To answer your question, use reset()

That said, it might not be the wisest solution for what you need to do, and @David Jesh has made a good suggestion.

Upvotes: 0

May be you can use a 'for' loop instead of 'foreach' and do something as below.

for($i=0;$i<count($hex_array);$i++)
{
  if($i>=(count($hex_array)-1))
  {
    $i=0;
  }
enter code here
}

Upvotes: 0

David Jashi
David Jashi

Reputation: 4511

Well, let's say N is length of your C array (colours) and P is your persons array.

Leave foreach loop alone and use plain old for loop with i as loop variable. Then for person P[i] colour will be C[i%N]

Upvotes: 1

Related Questions