We use the Iterator interface to make our objects easy to loop over with foreach. It helps us control how the object gives out its items one by one.
Iterator interface implementation in PHP
<?php class MyIterator implements Iterator { public function current() {} public function key() {} public function next() {} public function rewind() {} public function valid() {} } ?>
You must define all five methods: current(), key(), next(), rewind(), and valid().
These methods control how the loop moves through your data.
<?php class Numbers implements Iterator { private array $numbers = [1, 2, 3]; private int $position = 0; public function __construct() { $this->position = 0; } public function current() { return $this->numbers[$this->position]; } public function key() { return $this->position; } public function next() { $this->position++; } public function rewind() { $this->position = 0; } public function valid() { return isset($this->numbers[$this->position]); } } ?>
<?php class Letters implements Iterator { private array $letters = ['a', 'b', 'c']; private int $index = 0; public function current() { return $this->letters[$this->index]; } public function key() { return $this->index; } public function next() { $this->index++; } public function rewind() { $this->index = 0; } public function valid() { return isset($this->letters[$this->index]); } } ?>
This program creates a DaysOfWeek object that can be looped with foreach. It prints each day with its position.
<?php class DaysOfWeek implements Iterator { private array $days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']; private int $position = 0; public function __construct() { $this->position = 0; } public function current() { return $this->days[$this->position]; } public function key() { return $this->position; } public function next() { $this->position++; } public function rewind() { $this->position = 0; } public function valid() { return isset($this->days[$this->position]); } } $week = new DaysOfWeek(); foreach ($week as $key => $day) { echo "$key: $day\n"; } ?>
Remember to reset your position in rewind() so the loop starts from the beginning.
valid() should return true if the current position is valid, false otherwise.
Using isset() in valid() is a simple way to check if the current item exists.
The Iterator interface lets your object be used in foreach loops.
You must implement five methods to control the loop.
This helps you make custom collections easy and safe to loop through.
Practice
Iterator interface in PHP?Solution
Step 1: Recall Iterator interface methods
The Iterator interface requires implementing rewind(), current(), key(), next(), and valid() methods.Step 2: Identify the method not in Iterator
The sort() method is not part of the Iterator interface; it is unrelated to iteration.Final Answer:
sort() -> Option AQuick Check:
Iterator methods exclude sort() [OK]
- Confusing sort() as part of Iterator
- Forgetting to implement key() or valid()
- Thinking rewind() is optional
MyIterator that implements the Iterator interface?Solution
Step 1: Recall PHP interface implementation syntax
In PHP, a class implements an interface using the keyword 'implements'.Step 2: Check each option's syntax
class MyIterator implements Iterator { } uses 'implements' correctly. The other options use invalid keywords or syntax.Final Answer:
class MyIterator implements Iterator { } -> Option AQuick Check:
Use 'implements' keyword for interfaces [OK]
- Using 'extends' instead of 'implements' for interfaces
- Using 'uses' or 'interface' keywords incorrectly
- Missing curly braces after class declaration
$items = ['a', 'b', 'c'];
class MyIterator implements Iterator {
private array $items;
private int $index = 0;
public function __construct(array $items) {
$this->items = $items;
}
public function current() {
return $this->items[$this->index];
}
public function key() {
return $this->index;
}
public function next(): void {
$this->index++;
}
public function rewind(): void {
$this->index = 0;
}
public function valid(): bool {
return isset($this->items[$this->index]);
}
}
$iterator = new MyIterator($items);
foreach ($iterator as $key => $value) {
echo "$key:$value ";
}Solution
Step 1: Understand the iterator implementation
The class stores items and uses an index to track position. Methods current(), key(), next(), rewind(), and valid() are correctly implemented.Step 2: Trace the foreach loop output
foreach uses key() and current() to print "key:value" pairs. Indexes 0,1,2 correspond to 'a','b','c'. Output is "0:a 1:b 2:c "Final Answer:
0:a 1:b 2:c -> Option BQuick Check:
Iterator keys and values match array indexes and elements [OK]
- Confusing keys with values
- Forgetting to implement valid() correctly
- Expecting output without spaces
class BrokenIterator implements Iterator {
private array $data = [1, 2, 3];
private int $pos = 0;
public function current() {
return $this->data[$this->pos];
}
public function key() {
return $this->pos;
}
public function next() {
$this->pos++;
}
public function rewind() {
$this->pos = 0;
}
public function valid() {
return $this->pos < count($this->data);
}
}What is the main issue that could cause unexpected behavior when using this iterator in a foreach loop?
Solution
Step 1: Check method signatures against Iterator interface
Iterator interface requires next() and rewind() to have void return type declarations.Step 2: Identify missing return types
In the code, next() and rewind() lack ': void' return type, which can cause compatibility issues in strict mode.Final Answer:
Missing void return types in next() and rewind() -> Option DQuick Check:
next() and rewind() must declare void return type [OK]
- Ignoring return type declarations
- Thinking valid() must return integer
- Confusing isset() and count() usage in valid()
EvenNumbers that iterates over only even numbers from a given array. Which implementation of the valid() method correctly skips odd numbers during iteration?Solution
Step 1: Understand the goal of skipping odd numbers
The iterator must advance the index until it points to an even number or end of array.Step 2: Analyze each valid() implementation
public function valid(): bool { while (isset($this->items[$this->index]) && $this->items[$this->index] % 2 !== 0) { $this->index++; } return isset($this->items[$this->index]); } uses a while loop to skip odd numbers by incrementing index, then checks if current index exists. The other options do not skip odd numbers properly.Final Answer:
while loop in valid() to skip odd numbers -> Option CQuick Check:
valid() must skip odd values to find even numbers [OK]
- Returning true without skipping odd numbers
- Not checking if index exists before accessing array
- Using valid() only to check index range
Ready to prove it?
Pass the test and this pattern moves unknown
