PHP 8.5.0 Beta 3 available for testing

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

User Contributed Notes 3 notes

up
3
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
2
rkos... ยถ
11 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
0
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.
To Top