php.net |  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: -
Votes:1
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
Have you experienced this issue?
Rate the importance of this bug to you:

 [2021-06-17 14:47 UTC] php at yopmail dot com
Description:
------------
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: https://3v4l.org/sM8A5 (note: there was a Notice before PHP 7)

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

Test script:
---------------
<?php

$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:
----------------
0
1
2
3
{"0":true,"3":true}

Actual result:
--------------
0
1
3
{"0":true,"2":false,"3":true}

Patches

Add a Patch

Pull Requests

Add a Pull Request

 
PHP Copyright © 2001-2021 The PHP Group
All rights reserved.
Last updated: Sun Aug 01 15:01:24 2021 UTC