-1

I have a filter iterator. How can a unset a give value in it. I have tried unset($list[$key]), but that gives me an error : Cannot use object of type Filter as array

1
  • 1
    Show us the code you tried. Commented May 17, 2023 at 18:18

1 Answer 1

2

The documentation states that the FilterIterator "filters out unwanted values", and the logic behind that is in the accept() method which you must implement.

So you don't unset anything, you just reject (or not accept, technically) values you don't want.

class DoctorFilter extends FilterIterator
{
    public function accept(): bool
    {
        $obj = $this->getInnerIterator()->current();
        
        return is_string($obj) && str_starts_with($obj, 'Dr.');
    }
}

$people = [
    'Dr. Jekyll',
    'Mr. Hyde', // This item will be removed
    'Dr. Frankenstein',
];

foreach (new DoctorFilter(new ArrayIterator($people)) as $item) {
    echo $item.PHP_EOL;
}

/*
Outputs:

Dr. Jekyll
Dr. Frankenstein
*/

Demo: https://3v4l.org/ieTAP#v8.2.6

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.