📖 Scenario: You are creating a simple collection class in PHP that holds a list of fruits. You want to make this class iterable so you can loop through the fruits easily.
🎯 Goal: Build a PHP class called FruitCollection that implements the Iterator interface to allow looping over the fruits.
📋 What You'll Learn
Create a class called FruitCollection with a private array property $fruits containing exactly these fruits: 'Apple', 'Banana', 'Cherry'
Add a private integer property $position to track the current position in the iterator
Implement all required methods of the Iterator interface: current(), key(), next(), rewind(), and valid()
In the rewind() method, reset $position to 0
In the valid() method, check if the current position is valid in the $fruits array
Use a foreach loop to iterate over an instance of FruitCollection and print each fruit
💡 Why This Matters
🌍 Real World
Custom iterable classes are useful when you want to create your own collections or data structures that behave like arrays but have extra features.
💼 Career
Understanding how to implement Iterator is important for PHP developers working with custom data containers, frameworks, or libraries that require iterable objects.
Progress0 / 4 steps
1
Create the FruitCollection class with fruits array
Create a PHP class called FruitCollection with a private array property $fruits containing exactly these fruits: 'Apple', 'Banana', 'Cherry'. Also add a private integer property $position initialized to 0.
PHP
Hint
Define the class and properties exactly as described. Use PHP 7.4+ typed properties.
2
Implement the rewind() and current() methods
Inside the FruitCollection class, implement the rewind() method to reset $position to 0. Also implement the current() method to return the fruit at the current $position.
PHP
Hint
Remember rewind() resets the position. current() returns the item at the current position.
3
Implement key(), next(), and valid() methods
Inside the FruitCollection class, implement the key() method to return the current $position. Implement the next() method to increment $position by 1. Implement the valid() method to check if $position is a valid index in the $fruits array.
PHP
Hint
Use isset() in valid() to check if the position is valid.
4
Create instance and print fruits using foreach
Create an instance of FruitCollection called $fruits. Use a foreach loop to iterate over $fruits and print each fruit on its own line using echo.
PHP
Hint
Use foreach ($fruits as $fruit) and echo $fruit . "\n"; to print each fruit on a new line.
Practice
(1/5)
1. Which of the following methods is NOT required when implementing the Iterator interface in PHP?
easy
A. sort()
B. current()
C. next()
D. rewind()
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.
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 A
Quick Check:
Use 'implements' keyword for interfaces [OK]
Hint: Use 'implements' keyword to implement interfaces in PHP [OK]
Common Mistakes:
Using 'extends' instead of 'implements' for interfaces
Using 'uses' or 'interface' keywords incorrectly
Missing curly braces after class declaration
3. What will be the output of the following PHP code?
$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 ";
}
medium
A. a:b c:d e:f
B. 0:a 1:b 2:c
C. 0:0 1:1 2:2
D. Error: Undefined variable
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 B
Quick Check:
Iterator keys and values match array indexes and elements [OK]
Hint: Trace index and current() output for each loop iteration [OK]
Common Mistakes:
Confusing keys with values
Forgetting to implement valid() correctly
Expecting output without spaces
4. Consider this broken iterator class:
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?
medium
A. The next() method does not have a void return type
B. The valid() method should use isset() instead of count()
C. The valid() method returns a boolean but should return an integer
D. The next() and rewind() methods lack return type declarations
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 D
Quick Check:
next() and rewind() must declare void return type [OK]
Hint: Check method signatures match interface exactly including return types [OK]
Common Mistakes:
Ignoring return type declarations
Thinking valid() must return integer
Confusing isset() and count() usage in valid()
5. You want to create a custom iterator EvenNumbers that iterates over only even numbers from a given array. Which implementation of the valid() method correctly skips odd numbers during iteration?
hard
A. public function valid(): bool {
return isset($this->items[$this->index]);
}
B. public function valid(): bool {
return $this->items[$this->index] % 2 === 0;
}
C. public function valid(): bool {
while (isset($this->items[$this->index]) && $this->items[$this->index] % 2 !== 0) {
$this->index++;
}
return isset($this->items[$this->index]);
}
D. public function valid(): bool {
return $this->index < count($this->items);
}
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 C
Quick Check:
valid() must skip odd values to find even numbers [OK]
Hint: Use a loop inside valid() to skip unwanted elements [OK]
Common Mistakes:
Returning true without skipping odd numbers
Not checking if index exists before accessing array
Using valid() only to check index range
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.