1

I have a while loop with a nested foreach loop, after the first while loop is run the array inside the foreach loop is being unset (or at least ceases to be an array).

Where I'm headed is an array of data for a bar chart which shows every day since a start date and the number of clicks by type (8 types) on each day. So I'm calculating the number of days from the start date to now, and for each day it checks the first array to see how many, if any, and what types of clicks there were on that day.

Here's the relevant bit of code...

$i=0;
while($i<=$numdays)
{
echo $date2->format('Y-m-d') . "<br>";

foreach($clicklist as $key => $clicklist)   {
      if ( $clicklist[clickdate] === $date2 ) {
      echo $clicklist[clicks]." clicks on ".$clicklist[type]." on that date<br>";
        }
       }

$date2->modify('+1 day');
$i++;
echo is_array($clicklist) ? 'Array<br>' : 'not an Array<br>';
}

$numdays is the number of days from the startdate to now (needed for one of the chart variables, $date2 is the startdate and $clicklist is the array of clicks/dates/types from the db. All the random echos are just so I can see what's going on - or not as the case may be.

The while loop works fine is isolation, the foreach loop also works fine outside the while loop (using a static date in place of the variable), but of course that's just a one time run.

From the manual, foreach resets the pointer back to the start automatically, so that's not an issue.

I'm missing something obvious I'm sure.. any guidance much appreciated.

1 Answer 1

2
foreach($clicklist as $key => $clicklist)

Is where your problem is. Do not reuse the name, change it for something such as

foreach($clicklist as $key => $cl)

otherwise by the end of your loop, $clicklist will be overwritten as the last element that was iterated.


Edit: on a related note, avoid accessing your array without quotes, such as in $clicklist[clickdate]. This could later on turn into a bug if you ever encounter a constant that has been defined with that same name. Use $clicklist['clickdate'] instead.

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

1 Comment

Thanks and thanks Arthur, the answer did the trick and the edit is a good point - will do.

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.