Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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.

share|improve this question
add comment

1 Answer

up vote 2 down vote accepted
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.

share|improve this answer
    
Thanks and thanks Arthur, the answer did the trick and the edit is a good point - will do. –  Craig Jun 28 '13 at 4:59
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.