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.

NoRewindIterator and EmptyIterator

NoRewindIterator and EmptyIterator - PHP Tutorial

From the course: Learning the Standard PHP Library

Start my 1-month free trial

NoRewindIterator and EmptyIterator

- Let's take a quick look at two unusual iterators: NoRewindIterator and EmptyIterator. This is norewind.php, which you can find in the chapter six folder of the exercise files. It contains an ArrayIterator and two foreach loops to display the values. If we load this into a browser, the contents of the ArrayIterator are displayed twice. There's no need to rewind the iterator before using the second loop because foreach calls it automatically. However, let's see what happens when we chain our ArrayIterator with an instance of NoRewindIterator. So we'll add a new line on line three, and $sports, new NoRewindIterator, we'll pass it our ArrayIterator, save the page and refresh. This time the first loop works, but the second one has no values. Once an instance of NoRewindIterator gets to the end of the data, it can't be rewound. But what happens if we try to rewind it explicitly by calling the rewind() method? Let's try that before the second loop. So $sports, and we invoke the rewind()…

Contents