ArrayIterator::offsetUnset

(PHP 5, PHP 7, PHP 8)

ArrayIterator::offsetUnsetオフセットの値を削除する

説明

public ArrayIterator::offsetUnset(mixed $key): void

オフセットの値を削除します。

反復処理を実行中の場合、かつ現在の処理のインデックスを削除するために ArrayIterator::offsetUnset() を使った場合、 反復処理の位置は次のインデックスに移動します。 反復処理の位置が foreach ループの最後であってもインデックスは移動するため、 foreach ループの内部で ArrayIterator::offsetUnset() を使うと、 複数のインデックスがスキップされるかもしれません。

パラメータ

key

削除したいオフセット。

戻り値

値を返しません。

参考

add a note add a note

User Contributed Notes 3 notes

up
2
rkos...
10 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);
?>
up
2
olav at fwt dot no
12 years ago
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 results
up
0
Adil Baig @ AIdezigns
12 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.
To Top