28
loading...
This website collects cookies to deliver better user experience
foreach
loops that go over a collection of objects: iterators.Iterator
interface allows you to define a custom PHP behavior when props of a class instance are iterated over at every stage of a foreach
loop.current()
, which gets the currently iterated itemkey()
, which gets the currently iterated item keynext()
, which is used to move to the next position in the iterationrewind()
, which rewinds the position to the start of the iterationvalid()
, which tells you if the current position has a valueIterator
interface yourself for common day-to-day tasks that are not too business logic specific (for instance, iterating over files in a directory). For this kind of generic tasks, PHP provides predefined iterators that will make your life easier.ArrayIterator
, you can easily unset or modify values and keys when iterating over arrays and objects, as in =>// we assume that instances 1 to 4 were created earlier
$myList = new \ArrayIterator();
$myList->append($instance1);
$myList->append($instance2);
$myList->append($instance3);
$myList->append($instance4);
echo $myList->count(); // gives you the size of your list
while($myList->valid()) { // you'll recognize here one of the implemented methods from `Iterator` interface
$instanceItem = $myList->current();
// do something with instance keys/values here
$myList->next();
}
ArrayIterator
shows more capabilities when used with other iterators, like the FilterIterator
.FilterIterator
abstract class allows to create filter classes that can be then used in foreach
loops to conveniently retrieve values based on a condition during an iteration; this condition is defined in the implemented accept
method of the class that extends this iterator (cf https://www.php.net/manual/en/class.filteriterator.php).ArrayIterator
list; here we are using a simple list of numbers, but it can of course be an array of more complex objects on which you need to perform some operationsFilterIterator
$_filter
member that will be the variable that we will check against in our filteringFilterIterator
constructor and it implements the accept
method as required
class IsMultipleOfFilter extends \FilterIterator {
private int $_filter;
public function __construct(\Iterator $iterator, int $filter) {
parent::__construct($iterator);
$this->_filter = $filter;
}
public function accept(): bool {
return $this->current() % $this->_filter === 0;
}
}
$myList = new \ArrayIterator();
$myList->append(1);
$myList->append(2);
$myList->append(3);
$myList->append(4);
$myList->append(5);
$myList->append(6);
$myList->append(7);
$myList->append(8);
$myList->append(9);
$myList->append(10);
ArrayIterator
list and the filter to get only even numbers, for instance (the number 2) =>
$myFilteredList = new IsMultipleOfFilter($myList, 2);
foreach ($myFilteredList as $item) {
echo $item.PHP_EOL;
}