What is the Iterator interface in PHP?
Why Interviewers Ask This
Mid-level PHP roles require deep understanding of this topic. Interviewers ask this to separate candidates who truly understand the mechanics from those who only know surface-level concepts.
Answer
The Iterator interface allows objects to be iterated with a foreach loop just like arrays. Implement five methods: current() (return current element), key() (return current key), next() (move to next element), rewind() (reset to beginning), valid() (check if current position is valid). This allows custom data structures to be traversed naturally. The IteratorAggregate interface provides a simpler alternative — implement only getIterator() which returns an Iterator or array. PHP's Generators (using yield) provide an easy way to create lazy iterators without implementing the full Iterator interface.
Pro Tip
If you're unsure about a detail, say so honestly and explain your reasoning. Interviewers respect candidates who can think through uncertainty rather than bluffing.