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 Answer
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
*/