From the course: Learning the Standard PHP Library

Unlock the full course today

Join today to access over 22,600 courses taught by industry experts or purchase this course individually.

Creating a repeat sequence with InfiniteIterator

Creating a repeat sequence with InfiniteIterator - PHP Tutorial

From the course: Learning the Standard PHP Library

Start my 1-month free trial

Creating a repeat sequence with InfiniteIterator

- The InfiniteIterator class sounds like a programmer's nightmare. But the idea is to handle repetitive sequences without the need to constantly rewind the iterator. The simple way to prevent it from running out of control is to chain it with LimitIterator. I've opened infinite.php which you can find in the ch06 folder of the Exercise Files. It contains an array with the days of the week. A repeating pattern that we're all familiar with. To use this with an iterator, we first need to convert the array with ArrayIterator. So we'll use the same variable, days, new ArrayIterator, and we pass it the array. We can then chain this with InfiniteIterator. If we were to use days in a foreach loop without any further control, it would keep running forever. Or at least until the script times out after 30 seconds. We don't want that to happen, so we can restrict the number of repetitions using LimitIterator. Let's say today's Wednesday, and we want to display the days of the coming week. So days,…

Contents