When unsetting elements as you go it will not remove the second index of the Array being worked on. Im not sure exactly why but there is some speculations that when calling unsetOffset(); it resets the pointer aswell.
<?php
$a = new ArrayObject( range( 0,9 ) );
$b = new ArrayIterator( $a );
for ( $b->rewind(); $b->valid(); $b->next() )
{
echo "#{$b->key()} - {$b->current()} - \r\n";
$b->offsetUnset( $b->key() );
}
?>
To avoid this bug you can call offsetUnset in the for loop
<?php
/*** ... ***/
for ( $b->rewind(); $b->valid(); $b->offsetUnset( $b->key() ) )
{
/*** ... ***/
?>
Or unset it directly in the ArrayObject
<?php
/*** ... ***/
$a->offsetUnset( $b->key() );
/*** ... ***/
?>
which will produce correct resultsArrayIterator::offsetUnset
(PHP 5, PHP 7, PHP 8)
ArrayIterator::offsetUnset — Unset value for an offset
Description
Unsets a value for an offset.
If iteration is in progress, and ArrayIterator::offsetUnset() is used to
unset the current index of iteration, the iteration position will be advanced to the next index.
Since the iteration position is also advanced at the end of a
foreach loop body, use of
ArrayIterator::offsetUnset() inside a
foreach loop may result in
indices being skipped.
Parameters
key-
The offset to unset.
Return Values
No value is returned.
See Also
- ArrayIterator::offsetGet() - Get value for an offset
- ArrayIterator::offsetSet() - Set value for an offset
+add a note
User Contributed Notes 3 notes
olav at fwt dot no ¶
14 years ago
rkos... ¶
12 years ago
This is my solution for problem with offsetUnset
<?php
$a = new ArrayObject( range( 0,9 ) );
$b = new ArrayIterator( $a );
for ( $b->rewind(); $b->valid(); )
{
echo "#{$b->key()} - {$b->current()} - <br>\r\n";
if($b->key()==0 || $b->key()==1){
$b->offsetUnset( $b->key() );
}else {
$b->next();
}
}
var_dump($b);
?>
Adil Baig @ AIdezigns ¶
15 years ago
Make sure you use this function to unset a value. You can't access this iterator's values as an array. Ex:
<?php
$iterator = new \RecursiveIteratorIterator(new \RecursiveArrayIterator($arr));
foreach($iterator as $key => $value)
{
unset($iterator[$key]);
}
?>
Will return :
PHP Fatal error: Cannot use object of type RecursiveIteratorIterator as array
offsetUnset works properly even when removing items from nested arrays.