«

Oct 27

PHP Unset ArrayObject in foreach skip the following item – unexpected behaviour

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

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>