Filtering Iterators

Aug 18, 2009 Author: Developer

The FilterIterator class can be used to filter the items returned by an iteration:

class NumberFilter extends 
FilterIterator {
const FILTER_EVEN = 1;
const FILTER_ODD = 2;
private $_type;
function __construct($iterator, $odd_or_even = self::FILTER_EVEN)
{
$this->_type = $odd_or_even;parent::__construct($iterator);
}
function accept()
{
if ($this->_type == self::FILTER_EVEN) {
return ($this->current() % 2 == 0);
} else {
return ($this->current() % 2 == 1);
}
}
}
$numbers = new 
ArrayObject(range(0, 10));
$numbers_it = new 
ArrayIterator($numbers);
$it = new 
NumberFilter($numbers_it, NumberFilter::FILTER_ODD);
foreach ($it as $number) {
echo $number . PHP_EOL;
}

The accept() method simply determines whether any given element should be allowed in the iteration; note that FilterIterator already implements all of the methods of ArrayAccess, so that, effectively, from the outside our class can still be used as an array. This example outputs only the odd numbers stored in the array: 1 3 5 7 9


views 3709
  1. Add New Comment