When you unset the item from array in foreach, all works as expected
$array = [1,2,3,4]; foreach($array as $key => $value) { if($value === 2) { unset($array[$key]); continue; } echo "$value "; }
Will return following:
1 3 4
When you want to do the same with ArrayObject, you would expect exactly the same behaviour. Unfortunately, it is not the case.
class MainList extends \ArrayObject {} $arrayListObject = new MainList([1,2,3,4]); foreach($arrayListObject as $key => $value) { if($value === 2) { unset($arrayListObject[$key]); continue; } echo "$value "; }
Will return following:
1 4
See that the number 3 is missing in the response!!!
The reason for this is that the ArrayObject is behaving like object (not as an array) when looping through foreach.
This could be very confusing when you expect that that the foreach will process all the items.
The best option is to process it via
class MainList extends \ArrayObject {} $arrayListObject = new MainList([1,2,3,4]); foreach($arrayListObject->getArrayCopy() as $key => $value) { if($value === 2) { unset($arrayListObject[$key]); continue; } echo "$value "; }
Will return following (as expected):
1 3 4