PHP foreach by reference causes weird glitch when going through array of objects

If you iterate by reference, always unset the iteration variable afterwards:

foreach ($objects as &$object) {
      // some code
}
unset($object);

Excerpt from the foreach documentation:

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

If you want to understand why your code behaves the way it behaves, here is some further reading: References and foreach

Leave a Comment