|  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #81156 unset() on ArrayObject inside foreach skips next index
Submitted: 2021-06-17 14:47 UTC Modified: -
Avg. Score:1.0 ± 0.0
Reproduced:0 of 0 (0.0%)
From: php at yopmail dot com Assigned:
Status: Open Package: SPL related
PHP Version: 7.3.28 OS:
Private report: No CVE-ID: None
View Add Comment Developer Edit
Welcome! If you don't have a Git account, you can't do anything here.
You can add a comment by following this link or if you reported this bug, you can edit this bug over here.
Block user comment
Status: Assign to:
Bug Type:
From: php at yopmail dot com
New email:
PHP Version: OS:


 [2021-06-17 14:47 UTC] php at yopmail dot com
While looping over an ArrayObject with a foreach, if we unset an offset, then the next one gets skipped.
It works fine with a plain array.

Note: This looks similar to Bug #55157 and Bug #70246 but they were/are for ArrayIterator.
This may also be a "Documentation Problem", but that's at least surprising (a bit like Bug #80945, now fixed -- thanks nikic!)

More complete example: (note: there was a Notice before PHP 7)

Workaround: Do not foreach over $ao directly but over $ao->getArrayCopy() or (array)$ao

Test script:

$ao = new ArrayObject([true, false, false, true]);

foreach ($ao as $key => $value) {
    echo $key, "\n";
    if (!$value) {
        unset($ao[$key]); // or $ao->offsetUnset($key);
echo json_encode($ao), "\n";

Expected result:

Actual result:


Add a Patch

Pull Requests

Add a Pull Request

PHP Copyright © 2001-2021 The PHP Group
All rights reserved.
Last updated: Sun Sep 19 14:03:37 2021 UTC