Why php iteration by reference returns a duplicate last record?

前端 未结 1 531
夕颜
夕颜 2020-11-29 12:13

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:

            


        
相关标签:
1条回答
  • 2020-11-29 12:47

    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

    0 讨论(0)
提交回复
热议问题