Tech Blog :: PHP foreach/reference oddities
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?
Google: TheBuckSt0p
Facebook: BenBuckman
LinkedIn
Github: newleafdigital
@thebuckst0p
Delicious: thebuckst0p
Drupal.org: thebuckst0p
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()."
see explaination here:
http://i-code-today.blogspot.com/2009/02/php-array-foreach-loop-with-ref...
Post new comment
Don't bother putting in spam links. They'll be set to
rel=nofollowand will be removed and reported as spam shortly after submitting.