ArrayIterator::offsetUnset

(PHP 5, PHP 7, PHP 8)

ArrayIterator::offsetUnset β€” БбрасываСт Π·Π½Π°Ρ‡Π΅Π½ΠΈΠ΅ ΠΏΠΎ ΡΠΌΠ΅Ρ‰Π΅Π½ΠΈΡŽ

ОписаниС

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

БбрасываСт Π·Π½Π°Ρ‡Π΅Π½ΠΈΠ΅ ΠΏΠΎ ΡΠΌΠ΅Ρ‰Π΅Π½ΠΈΡŽ.

Если итСрация выполняСтся ΠΈ ArrayIterator::offsetUnset() ΠΈΡΠΏΠΎΠ»ΡŒΠ·ΡƒΠ΅Ρ‚ΡΡ для сброса Ρ‚Π΅ΠΊΡƒΡ‰Π΅Π³ΠΎ индСкса ΠΈΡ‚Π΅Ρ€Π°Ρ†ΠΈΠΈ, позиция ΠΈΡ‚Π΅Ρ€Π°Ρ†ΠΈΠΈ Π±ΡƒΠ΄Π΅Ρ‚ смСщСна ΠΊ ΡΠ»Π΅Π΄ΡƒΡŽΡ‰Π΅ΠΌΡƒ индСксу. ΠŸΠΎΡΠΊΠΎΠ»ΡŒΠΊΡƒ позиция ΠΈΡ‚Π΅Ρ€Π°Ρ†ΠΈΠΈ Ρ‚Π°ΠΊΠΆΠ΅ смСщаСтся Π² ΠΊΠΎΠ½Ρ†Π΅ foreach Π² Ρ‚Π΅Π»Π΅ Ρ†ΠΈΠΊΠ»Π°, использованиС ArrayIterator::offsetUnset() Π²Π½ΡƒΡ‚Ρ€ΠΈ Ρ†ΠΈΠΊΠ»Π° foreach ΠΌΠΎΠΆΠ΅Ρ‚ привСсти ΠΊ пропуску индСксов.

Бписок ΠΏΠ°Ρ€Π°ΠΌΠ΅Ρ‚Ρ€ΠΎΠ²

key

Π‘ΠΌΠ΅Ρ‰Π΅Π½ΠΈΠ΅ для сброса.

Π’ΠΎΠ·Π²Ρ€Π°Ρ‰Π°Π΅ΠΌΡ‹Π΅ значСния

Ѐункция Π½Π΅ Π²ΠΎΠ·Π²Ρ€Π°Ρ‰Π°Π΅Ρ‚ значСния послС выполнСния.

Π‘ΠΌΠΎΡ‚Ρ€ΠΈΡ‚Π΅ Ρ‚Π°ΠΊΠΆΠ΅

  • ArrayIterator::offsetGet() - ΠŸΠΎΠ»ΡƒΡ‡Π°Π΅Ρ‚ Π·Π½Π°Ρ‡Π΅Π½ΠΈΠ΅ для смСщСния
  • ArrayIterator::offsetSet() - УстанавливаСт Π·Π½Π°Ρ‡Π΅Π½ΠΈΠ΅ для смСщСния
οΌ‹Π”ΠΎΠ±Π°Π²ΠΈΡ‚ΡŒ

ΠŸΡ€ΠΈΠΌΠ΅Ρ‡Π°Π½ΠΈΡ ΠΏΠΎΠ»ΡŒΠ·ΠΎΠ²Π°Ρ‚Π΅Π»Π΅ΠΉ 3 notes

up
2
olav at fwt dot no ΒΆ
14 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
1
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);
?>
up
-1
Adil Baig @ AIdezigns ΒΆ
14 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.