Take the 2-minute tour ×

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.

share|improve this question
show us your code –  Jacek Kaniuk Aug 23 '11 at 9:19
This shouldn't happen, can you provide some example? –  XzKto Aug 23 '11 at 9:20
add comment

1 Answer

up vote 12 down vote accepted

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

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

share|improve this answer
add comment

Your Answer


