Why php iteration by reference returns a duplicate

2019-01-08 00:40发布

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.

标签: php iteration
1条回答
趁早两清
2楼-- · 2019-01-08 01:09

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

查看更多
登录 后发表回答