ArrayObject implements IteratorAggregate , which means it has a getIterator () method that returns an iterator.
php foreach loop will automatically load the iterator by calling the getIterator () method so that you can iterate over the iterator. This is convenient, but you need to get a reference to this iterator in order to call the offsetUnset () method on the iterator itself. The main thing here is to call the iterators offsetUnset () method, not the ArrayObjects offsetUnset () method.
$ao = new ArrayObject(); $ao[] = 9; $iter = $ao->getIterator(); foreach ($iter as $k => $v) $iter->offsetUnset($k);
The base ArrayObject that iterates through the iteration will be mutated, so if you have more than one active iterator at the same time over the same Arrayobject, you will still encounter the same error.
The rationale for this is most likely that iterators can be memory efficient and should not copy the underlying ArrayObject because the copy is the only simple solution to the complex task of deciding what the current position of the iterator should be when things are added or removed from base array.
source share