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.

Converting between arrays and iterators

Converting between arrays and iterators - PHP Tutorial

From the course: Learning the Standard PHP Library

Start my 1-month free trial

Converting between arrays and iterators

- Because SPL iterators allow you to traverse directories and other structures with a for each loop, just like an array, it's easy to forget that arrays and iterators are not the same. You can't chain iterators onto an array without first converting the array to an iterator. Nor can you pass an iterator as an argument to an array function. To show you what I mean, I have opened array.php, which contains a simple array called languages and then loops over it. You can find a copy of this file in the chapter four folder of the exercise files. So let's just load this into the browser. And we get all of the elements of the array displayed. Nothing surprising about that. That's how arrays work. But let's say we want to limit the range of values displayed. Let's try to chain LimitIterator to the array. So a new line on line three, we'll call it languages again. New LImitIterator, and then we'll pass it our languages array. The second argument is where you want to begin, counting from zero…

Contents