Bird
Raised Fist0
PHPprogramming~20 mins

Iterator interface implementation in PHP - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Iterator Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of a simple Iterator implementation
What is the output of this PHP code that implements Iterator to loop over an array of colors?
PHP
<?php
class ColorIterator implements Iterator {
    private array $colors;
    private int $position = 0;

    public function __construct(array $colors) {
        $this->colors = $colors;
    }

    public function current(): string {
        return $this->colors[$this->position];
    }

    public function key(): int {
        return $this->position;
    }

    public function next(): void {
        $this->position++;
    }

    public function rewind(): void {
        $this->position = 0;
    }

    public function valid(): bool {
        return isset($this->colors[$this->position]);
    }
}

$colors = ['red', 'green', 'blue'];
$iterator = new ColorIterator($colors);
foreach ($iterator as $key => $color) {
    echo "$key:$color ";
}
?>
A0:red 1:green 2:blue
Bred green blue
C0:red 1:green
D1:red 2:green 3:blue
Attempts:
2 left
💡 Hint
Remember the Iterator interface methods control the keys and values during foreach.
🧠 Conceptual
intermediate
1:30remaining
Understanding valid() method in Iterator
What is the role of the valid() method in a PHP Iterator implementation?
AIt returns the current element's value.
BIt resets the iterator to the first element.
CIt checks if the current position is valid and iteration should continue.
DIt moves the iterator to the next element.
Attempts:
2 left
💡 Hint
Think about how foreach knows when to stop looping.
🔧 Debug
advanced
2:00remaining
Identify the error in this Iterator implementation
What error will this PHP code produce when trying to iterate over the object?
PHP
<?php
class NumberIterator implements Iterator {
    private array $numbers = [1, 2, 3];
    private int $pos = 0;

    public function current() {
        return $this->numbers[$this->pos];
    }

    public function key() {
        return $this->pos;
    }

    public function next() {
        $this->pos++;
    }

    public function rewind() {
        $this->pos = 0;
    }

    // Missing valid() method
}

$iter = new NumberIterator();
foreach ($iter as $num) {
    echo $num . ' ';
}
?>
AOutputs: 1 2 3
BFatal error: Class must implement method valid() from Iterator interface
CWarning: Undefined offset 3
DNo output, infinite loop
Attempts:
2 left
💡 Hint
Check if all required Iterator methods are implemented.
📝 Syntax
advanced
1:30remaining
Which option correctly implements the rewind() method?
Choose the correct rewind() method implementation for a PHP Iterator that resets position to zero.
Apublic function rewind() { $this->position = 0; }
Bpublic function rewind() { return 0; }
Cpublic function rewind() { $this->position++; }
Dpublic function rewind() { unset($this->position); }
Attempts:
2 left
💡 Hint
rewind() should reset the iterator to the start.
🚀 Application
expert
3:00remaining
Custom Iterator to iterate only even numbers
Given this PHP Iterator class, what is the output when iterating over it?
PHP
<?php
class EvenNumberIterator implements Iterator {
    private array $numbers;
    private int $position = 0;

    public function __construct(array $numbers) {
        $this->numbers = $numbers;
        $this->rewind();
    }

    public function current(): int {
        return $this->numbers[$this->position];
    }

    public function key(): int {
        return $this->position;
    }

    public function next(): void {
        do {
            $this->position++;
        } while (isset($this->numbers[$this->position]) && $this->numbers[$this->position] % 2 !== 0);
    }

    public function rewind(): void {
        $this->position = 0;
        if (isset($this->numbers[$this->position]) && $this->numbers[$this->position] % 2 !== 0) {
            $this->next();
        }
    }

    public function valid(): bool {
        return isset($this->numbers[$this->position]);
    }
}

$nums = [1, 2, 3, 4, 5, 6];
$iter = new EvenNumberIterator($nums);
foreach ($iter as $key => $val) {
    echo "$key:$val ";
}
?>
A2:3 4:5 6:7
B0:1 1:2 2:3 3:4 4:5 5:6
C0:2 1:4 2:6
D1:2 3:4 5:6
Attempts:
2 left
💡 Hint
The iterator skips odd numbers by advancing position until an even number is found.

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

  1. Step 1: Recall Iterator interface methods

    The Iterator interface requires implementing rewind(), current(), key(), next(), and valid() methods.
  2. Step 2: Identify the method not in Iterator

    The sort() method is not part of the Iterator interface; it is unrelated to iteration.
  3. Final Answer:

    sort() -> Option A
  4. Quick Check:

    Iterator methods exclude sort() [OK]
Hint: Remember: Iterator needs rewind, current, key, next, valid only [OK]
Common Mistakes:
  • Confusing sort() as part of Iterator
  • Forgetting to implement key() or valid()
  • Thinking rewind() is optional
2. Which of the following is the correct syntax to declare a class MyIterator that implements the Iterator interface?
easy
A. class MyIterator implements Iterator { }
B. class MyIterator extends Iterator { }
C. class MyIterator uses Iterator { }
D. class MyIterator interface Iterator { }

Solution

  1. Step 1: Recall PHP interface implementation syntax

    In PHP, a class implements an interface using the keyword 'implements'.
  2. Step 2: Check each option's syntax

    class MyIterator implements Iterator { } uses 'implements' correctly. The other options use invalid keywords or syntax.
  3. Final Answer:

    class MyIterator implements Iterator { } -> Option A
  4. 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

  1. 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.
  2. 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 "
  3. Final Answer:

    0:a 1:b 2:c -> Option B
  4. 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

  1. Step 1: Check method signatures against Iterator interface

    Iterator interface requires next() and rewind() to have void return type declarations.
  2. Step 2: Identify missing return types

    In the code, next() and rewind() lack ': void' return type, which can cause compatibility issues in strict mode.
  3. Final Answer:

    Missing void return types in next() and rewind() -> Option D
  4. 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

  1. 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.
  2. 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.
  3. Final Answer:

    while loop in valid() to skip odd numbers -> Option C
  4. 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 unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard