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
View Add Comment Developer Edit
Anyone can comment on a bug. Have a simpler test case? Does it work for you on a different platform? Let us know!
Just going to say 'Me too!'? Don't clutter the database with that please — but make sure to vote on the bug!
Your email address:
MUST BE VALID
Solve the problem:
36 - 7 = ?
Subscribe to this entry?

 
 [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: Fri Sep 24 19:03:38 2021 UTC