views:

131

answers:

2

Explanation

I have a multidimensional array that is iterated over to created a categorized view of people with different research interests. The main array look something like this:

Array
(
    ...
    ['Cell Biology']      => Array(4 elements)
    ['Molecular']         => Array(6 elements)
    ['Biology Education'] => Array(14 elements)
    ['Plant Biology']     => Array(19 elements)  <--- Last element in array
)

I know that the entire array is intact and correctly structured. The only information that is inside these array is an user id, like so:

Array ('Plant Biology') 19 elements
(
    [0] => 737
    [1] => 742
    [2] => 748
    ...
)

My problem is that after i run the main array through a foreach loop the last 'sub-array' gets messed up. By messed up I mean that what you see about instead look like:

String (13 characters) 'Plant Biology'

This is without doing at all anything inside the loop with to the array that gets corrupted.

Any tips to what it might be?

PHP Code

  // ---> Array is OK here
  echo "<h2>Research divided</h2>";
  // Loop areas and list them in 2 columns
  foreach($research['areas'] as $area => $areaArray) {
      // ---> Here it is already corrupted
      $count = count($areaArray);
      if($count > 0) {
          echo "<h3>$area</h3><hr/>";
          echo "<ul>";
          // Loop users within areas, divided up in 2 columns
          for($i=0 ; $i<$count ; $i++) {
              $uid = $areaArray[$i];
              echo "<li>$uid</li>";
          }
          echo "</ul>";
      }
  }
+1  A: 

It looks like an error that can occur if you loop over the array previously by referance using the same variable name for the value.

So if earlier in your code $areaArray is used in a foreach by referance it might corrupt your data.

Make sure both variables in your foreach are not used previously or unset them before the loop.

Check out:

http://bugs.php.net/29992

For more info on this kind of problem.

Jai
That is the exact bug! THanks for the helpful link
WmasterJ
+1  A: 

Are $area or $areaArray being used in different function elsewhere in your script? Wht happens if you rename them to $loop_area and $loop_areaArray to prevent accidental overwriting of variables?

Pekka
WmasterJ
After being bitten by this multiple times, I promised never to use foreach loops. However, the solution is to make sure you always unset the variables created after the loop. That's not very convenient, so I just don't use foreach.
Juan Mendes