Question

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?

Was it helpful?

Solution

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]

OTHER TIPS

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
}

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top