Bug #81156 [NEW]: unset() on ArrayObject inside foreach skips next index
From: php at yopmail dot com
Operating system:
PHP version: 7.3.28
Package: SPL related
Bug Type: Bug
Bug description:unset() on ArrayObject inside foreach skips next index
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 bug report at https://bugs.php.net/bug.php?id=81156&edit=1
--
Fix committed: https://bugs.php.net/fix.php?id=81156&r=fixed
Fixed in release: https://bugs.php.net/fix.php?id=81156&r=alreadyfixed
Need backtrace: https://bugs.php.net/fix.php?id=81156&r=needtrace
Need Reproduce Script: https://bugs.php.net/fix.php?id=81156&r=needscript
Try newer version: https://bugs.php.net/fix.php?id=81156&r=oldversion
Not developer issue: https://bugs.php.net/fix.php?id=81156&r=support
Expected behavior: https://bugs.php.net/fix.php?id=81156&r=notwrong
Not enough info: https://bugs.php.net/fix.php?id=81156&r=notenoughinfo
Submitted twice: https://bugs.php.net/fix.php?id=81156&r=submittedtwice
register_globals: https://bugs.php.net/fix.php?id=81156&r=globals
PHP version support discontinued: https://bugs.php.net/fix.php?id=81156&r=phptooold
Daylight Savings: https://bugs.php.net/fix.php?id=81156&r=dst
IIS Stability: https://bugs.php.net/fix.php?id=81156&r=isapi
Install GNU Sed: https://bugs.php.net/fix.php?id=81156&r=gnused
Floating point limitations: https://bugs.php.net/fix.php?id=81156&r=float
No Zend Extensions: https://bugs.php.net/fix.php?id=81156&r=nozend
MySQL Configuration Error: https://bugs.php.net/fix.php?id=81156&r=mysqlcfg
Thread (2 messages)
- php at yopmail dot com