Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why php iteration by reference returns a duplicate last record?

Tags:

iteration

php

I just spent 2 hours hunting a bug which apparently comes from a foreach iteration with &value. I have a multidimentional array and when a ran this:

   foreach($arrayOfJsonMods as &$item){
        //TODO memcached votes
   }

and PHP returned an array with the same element count, BUT with a DUPLICATE last record. Is there something i don't understand about this structure?

I ran the code on a different machine, and the result was the same.

like image 794
vasion Avatar asked Aug 23 '11 09:08

vasion


1 Answers

I'll guess that you're reusing &$item here and that you're stumbling across a behavior which has been reported as bug a thousand times but is the correct behavior of references, which is why the manual advises:

Reference of a $value and the last array element remain even after the foreach loop. It is recommended to destroy it by unset().

foreach($arrayOfJsonMods as &$item)
{
   //TODO memcached votes
}
unset($item);

See https://bugs.php.net/bug.php?id=29992

like image 148
deceze Avatar answered Oct 05 '22 15:10

deceze