PHP foreach/reference oddities

October 27, 2010

I encountered this weirdness today with some basic PHP:

Early in the script I had: (note the reference &$nid)

// validate
foreach($nids as $key => &$nid) {
  if (empty($nid)) unset($nids[$key]);
  if (! is_numeric($nid)) unset($nids[$key]);
  $nid = (int) $nid;
}

print_r($nids);

Outputs:

Array ( [0] => 81 [1] => 1199 )

Then later on…

  foreach($nids as $nid) {
    echo $nid;
  }

Outputs:

81 81

If I change the 2nd loop to:

  foreach($nids as &$nid) {
    echo $nid;
  }

then it outputs 81 and 1199 like it should.

Shouldn’t as $nid reset the variable so it’s no longer a reference?