Bug #70246 [Com]: ArrayIterator skips next element when current element is unset in foreach.

From: Date: Fri, 18 Mar 2016 11:45:17 +0000
Subject: Bug #70246 [Com]: ArrayIterator skips next element when current element is unset in foreach.
References: 1  Groups: php.bugs 
Request: Send a blank email to php-bugs+get-199918@lists.php.net to get a copy of this message
Edit report at https://bugs.php.net/bug.php?id=70246&edit=1 ID: 70246 Comment by: david at grudl dot com Reported by: arjen at react dot com Summary: ArrayIterator skips next element when current element is unset in foreach. Status: Open Type: Bug Package: SPL related Operating System: Linux PHP Version: 7.0.0beta3 Block user comment: N Private report: N New Comment: Similar bug with stdClass and ArrayIterator: https://3v4l.org/2A1pf Previous Comments: ------------------------------------------------------------------------ [2015-09-19 18:55:50] j dot tvr at centrum dot cz This is probably not a bug. When you unset current element, the internal array pointer moves to the next element. Therefore what you're doing is essentially equivalent to https://3v4l.org/rWQq8: <?php $ar = [1, 2, 3, 4, 5]; $it = new ArrayIterator($ar); foreach ($it as $k => $v) { if ($k === 0) $it->next(); // eq. to unset($it[0]); echo "\$ar[$k] = $v;\n"; } echo "\n"; print_r(iterator_to_array($it)); ------------------------------------------------------------------------ [2015-08-18 11:56:39] arjen at react dot com Expected and actual result are swapped, my mistake.. Expected result: -------------- int(1) int(2) int(3) int(4) int(5) --------- int(1) int(3) int(4) int(5) Actual result: ---------------- int(1) int(2) int(4) int(5) --------- int(1) int(3) int(4) int(5) ------------------------------------------------------------------------ [2015-08-12 12:34:15] arjen at react dot com Description: ------------ ArrayIterator skips next element when current element is unset in foreach. http://3v4l.org/uUoaH Test script: --------------- <?php $ar = [1,2,3,4,5]; $i = new ArrayIterator($ar); foreach ($i as $k => $e) { var_dump($e); if ($k === 1) { unset($i[$k]); } } echo '---------' . PHP_EOL; foreach ($i as $e) { var_dump($e); } Expected result: ---------------- int(1) int(2) int(4) int(5) --------- int(1) int(3) int(4) int(5) Actual result: -------------- int(1) int(2) int(3) int(4) int(5) --------- int(1) int(3) int(4) int(5) ------------------------------------------------------------------------ -- Edit this bug report at https://bugs.php.net/bug.php?id=70246&edit=1

« previous php.bugs (#199918) next »