2024 年日本 PHP 研討會

ArrayIterator::offsetUnset

(PHP 5, PHP 7, PHP 8)

ArrayIterator::offsetUnset取消設定指定位移的數值

說明

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

取消設定指定位移的數值。

如果迭代正在進行中,並且使用 ArrayIterator::offsetUnset() 來取消設定目前的迭代索引,則迭代位置將會前進到下一個索引。由於迭代位置也會在 foreach 迴圈主體的結尾處前進,因此在 foreach 迴圈內使用 ArrayIterator::offsetUnset() 可能會導致索引被跳過。

參數

鍵值 (key)

要取消設定的偏移量。

回傳值

不回傳任何值。

參見

新增註解

使用者貢獻的註解 3 則註解

olav at fwt dot no
13 年前
當您一邊迭代一邊取消設定元素時,它不會移除正在處理的陣列的第二個索引。我不確定確切原因,但有些推測認為,呼叫 unsetOffset(); 時,它也會重置指標。

<?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() );
}

?>

為了避免這個錯誤,您可以在 for 迴圈中呼叫 offsetUnset

<?php
/*** ... ***/
for ( $b->rewind(); $b->valid(); $b->offsetUnset( $b->key() ) )
{
/*** ... ***/
?>

或者直接在 ArrayObject 中取消設定
<?php
/*** ... ***/
$a->offsetUnset( $b->key() );
/*** ... ***/
?>

這樣會產生正確的結果
rkos...
10 年前
這是我的 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
13 年前
請務必使用此函式來取消設定值。您不能以陣列的方式存取此迭代器的值。例如:

<?php
$iterator
= new \RecursiveIteratorIterator(new \RecursiveArrayIterator($arr));

foreach(
$iterator as $key => $value)
{
unset(
$iterator[$key]);
}
?>

會回傳

PHP 致命錯誤:無法將 RecursiveIteratorIterator 類型的物件當作陣列使用

即使從巢狀陣列中移除項目,offsetUnset 也能正常運作。
To Top