Bug #81156 [Com]: unset() on ArrayObject inside foreach skips next index

From: Date: Fri, 30 Dec 2022 11:32:18 +0000
Subject: Bug #81156 [Com]: unset() on ArrayObject inside foreach skips next index
References: 1  Groups: php.bugs 
Request: Send a blank email to php-bugs+get-243286@lists.php.net to get a copy of this message
Edit report at https://bugs.php.net/bug.php?id=81156&edit=1

 ID:                 81156
 Comment by:         Arthur988Davis at gmail dot com
 Reported by:        php at yopmail dot com
 Summary:            unset() on ArrayObject inside foreach skips next
                     index
 Status:             Open
 Type:               Bug
 Package:            SPL related
 PHP Version:        7.3.28
 Block user comment: N
 Private report:     N

 New Comment:

Hello, Try this

Normally, foreach operates on a copy of your array so any changes you make, are made to that copy
and don't affect the actual array.

So you need to unset the values via $images[$key];

The reference on &$image prevents the loop from creating a copy of the array which would waste
memory.

(https://www.alaskasworld.kim/)github.com


Previous Comments:
------------------------------------------------------------------------
[2021-06-17 14:47:51] 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}


------------------------------------------------------------------------



--
Edit this bug report at https://bugs.php.net/bug.php?id=81156&edit=1


Thread (2 messages)

« previous php.bugs (#243286) next »