Full Stack LAMP - MEAN Developer, Python developer. Certified Azure Developer. Freelance programmer/consultant/trainer.

PHP FilterIterator Example

This abstract iterator filters out unwanted values. This class should be extended to implement custom iterator filters. The FilterIterator::accept() must be implemented in the subclass.

class OnlyActiveFilter extends FilterIterator
{
    public function accept()
    {

    }
}

In accept()method we will apply logic on whatever $this->current() method will return as shown below. In the below method we are testing against current element is active or not , depending on the response we are returning a Boolean true or false. If the result is false that element will be removed form the result and vice versa.

class OnlyActiveFilter extends FilterIterator
{
    public function accept()
    {
        $item = $this->current();

        if ($item['is_active'] == 1) {
            return true;
        }

        return false;
    }
}

How to use

$data = [['id' => 1,'name' => 'arjun','email' => '[email protected]','is_active' => 1],
         ['id' => 2,'name' => 'pravinh','email' => '[email protected]','is_active' => 0]];

$result = new OnlyActiveFilter(new ArrayIterator($data));

foreach ($result as $key => $value) {
	print_r($value);
}

// Array ( [id] => 1 [name] => arjun [email] => [email protected] [is_active] => 1 ) 

I hope you like this Post, Please feel free to comment below, your suggestion and problems if you face - we are here to solve your problems.

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments