Recall & Review
beginner
What is the purpose of the Iterator interface in PHP?
The Iterator interface allows an object to be looped over with foreach by defining methods to access elements one by one.
Click to reveal answer
beginner
Name the five methods that must be implemented when using the Iterator interface.
The five methods are:
current(), key(), next(), rewind(), and valid().Click to reveal answer
beginner
What does the
current() method do in an Iterator?It returns the current element in the collection that the iterator points to.
Click to reveal answer
intermediate
Explain the role of the
valid() method in the Iterator interface.The
valid() method checks if the current position is valid, meaning the iterator has not reached the end of the collection.Click to reveal answer
beginner
Why is implementing the Iterator interface useful in PHP?
It allows custom objects to be used in foreach loops, making code cleaner and easier to read when working with collections.
Click to reveal answer
Which method in the Iterator interface moves the pointer to the next element?
✗ Incorrect
The next() method advances the internal pointer to the next element.
What does the rewind() method do in an Iterator?
✗ Incorrect
rewind() resets the iterator to the start of the collection.
Which method returns the key of the current element in an Iterator?
✗ Incorrect
The key() method returns the key/index of the current element.
What should the valid() method return if the iterator has reached the end?
✗ Incorrect
valid() returns false when the iterator is past the last element.
Why implement Iterator instead of just using an array?
✗ Incorrect
Implementing Iterator lets custom objects be used in foreach loops.
Describe the five methods you must implement when creating a class that implements the Iterator interface in PHP.
Think about how the iterator moves and accesses elements.
You got /5 concepts.
Explain how implementing the Iterator interface can improve working with custom collections in PHP.
Consider how foreach works with arrays and how Iterator helps with objects.
You got /4 concepts.