|
php.net | support | documentation | report a bug | advanced search | search howto | statistics | random bug | login |
[2011-07-07 06:52 UTC] olav at fwt dot no
Description:
------------
ArrayIterator always skips the second element in the array when calling
offsetUnset(); on it while looping through.
Using the key from iterator and unsetting in the actual ArrayObject works as
expected.
Running php 5.3.5 on openSUSE 11.4
Replicated same bug on Debian 5 running PHP 5.2.6-1+lenny9.
php5 is installed as binary on both systems, SPL is builtin package.
Test script:
---------------
<?php
// Create a array range from 0 to 9
$a = new ArrayObject( range( 0,9 ) );
$b = new ArrayIterator( $a );
for ( $b->rewind(); $b->valid(); $b->next() )
{
echo "#{$b->current()} - \r\n";
$b->offsetUnset( $b->key() );
}
?>
Expected result:
----------------
Expected a list of from 0 to 9 echoed out.
Actual result:
--------------
Lists out 0 and then 2-9 leaving index 1 untouched in the original ArrayObject.
PatchesPull Requests
Pull requests:
HistoryAllCommentsChangesGit/SVN commits
|
|||||||||||||||||||||||||||||||||||||
Copyright © 2001-2025 The PHP GroupAll rights reserved. |
Last updated: Tue Oct 28 00:00:02 2025 UTC |
Just to narrow the scope of the bug a bit: $a = range( 0,9 ); $b = new ArrayIterator( $a ); foreach($b as $k=>$v) { $b->offsetUnset($k); } var_dump($b->getArrayCopy()); // why is 1 still around?Sorry, I should clarify that the code above gives: array(1) { [1]=> int(1) } Whereas you'd probably expect: array(0) { }I have the same problem, used this code: $items = new ArrayObject(array(1, 2, 3, 4, 5)); foreach($items as $item) { if(in_array($item, array(2, 3, 4))) { $items->offsetUnset($item); } } var_dump($items->getArrayCopy()); Expected result: array(1, 5), actual result: array(1, 3, 5).Please ignore my comment above. The offsetUnset() method unsets elements using their index. Changing the code to this gives the expected result (0, 4): $items = new ArrayObject(array(0, 1, 2, 3, 4)); foreach($items->getArrayCopy() as $item) { if(in_array($item, array(1, 2, 3))) { $items->offsetUnset($item); } } var_dump($items->getArrayCopy());It seems that calling `ArrayIterator::offsetUnset` moves the internal pointer to the next element when removing the first index: $a = range( 0,3 ); $b = new ArrayIterator( $a ); for ($b->rewind(); $b->valid(); ) { echo "{$b->key()} => {$b->current()}\n"; $b->offsetUnset($b->key()); } var_dump($b->getArrayCopy());