Tech Blog :: PHP foreach/reference oddities


Oct 27 '10 4:43pm
Tags

PHP foreach/reference oddities

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?

I've just encountered this same weirdness, and I remembered this post, so thank you! :)

I've checked the manual of the foreach, and I've found a warning about this behavior:
"Reference of a $value (in your case: $nid) and the last array element remain even after the foreach loop. It is recommended to destroy it by unset()."

Post new comment

Don't bother putting in spam links. They'll be set to rel=nofollow and will be removed and reported as spam shortly after submitting.

The content of this field is kept private and will not be shown publicly.
CAPTCHA
Are you human?