Bird
Raised Fist0
PHPprogramming~20 mins

IteratorAggregate interface in PHP - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
IteratorAggregate Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of IteratorAggregate with simple array
What is the output of this PHP code using IteratorAggregate?
PHP
<?php
class MyCollection implements IteratorAggregate {
    private array $items = [1, 2, 3];
    public function getIterator(): Traversable {
        return new ArrayIterator($this->items);
    }
}
$collection = new MyCollection();
foreach ($collection as $item) {
    echo $item . ' ';
}
A1 2 3
BArrayIterator Object
CError: getIterator must return an array
D1,2,3
Attempts:
2 left
💡 Hint
Remember that IteratorAggregate requires getIterator() to return an iterator object.
❓ Predict Output
intermediate
2:00remaining
Output when getIterator returns a generator
What will this PHP code output when using IteratorAggregate with a generator?
PHP
<?php
class GenCollection implements IteratorAggregate {
    public function getIterator(): Traversable {
        yield 10;
        yield 20;
        yield 30;
    }
}
$gen = new GenCollection();
foreach ($gen as $value) {
    echo $value . '-';
}
A10-20-30-
BArrayIterator Object
CFatal error: getIterator must return an Iterator object
D10 20 30
Attempts:
2 left
💡 Hint
Generators implement Traversable and can be returned by getIterator.
🔧 Debug
advanced
2:00remaining
Identify the error in IteratorAggregate implementation
What error will this PHP code produce?
PHP
<?php
class BadCollection implements IteratorAggregate {
    private array $data = [5, 6, 7];
    public function getIterator(): array {
        return $this->data;
    }
}
$bad = new BadCollection();
foreach ($bad as $item) {
    echo $item;
}
ASyntax error: missing semicolon
BOutputs: 567
CFatal error: getIterator must return an instance of Traversable
DTypeError: Cannot convert array to string
Attempts:
2 left
💡 Hint
Check the return type of getIterator method.
📝 Syntax
advanced
2:00remaining
Which option correctly implements IteratorAggregate?
Which of the following PHP code snippets correctly implements IteratorAggregate?
Aclass C implements IteratorAggregate { public function getIterator(): array { return [1,2]; } }
Bclass C implements IteratorAggregate { public function getIterator(): Traversable { return new ArrayIterator([1,2]); } }
Cclass C implements IteratorAggregate { public function getIterator(): Traversable { return [1,2]; } }
Dclass C implements IteratorAggregate { public function getIterator() { return [1,2]; } }
Attempts:
2 left
💡 Hint
getIterator must return Traversable, not array.
🚀 Application
expert
3:00remaining
Count items using IteratorAggregate and Countable
Given this PHP class implementing IteratorAggregate and Countable, what is the output of the code?
PHP
<?php
class CountableCollection implements IteratorAggregate, Countable {
    private array $elements = ['a', 'b', 'c', 'd'];
    public function getIterator(): Traversable {
        return new ArrayIterator($this->elements);
    }
    public function count(): int {
        return count($this->elements);
    }
}
$col = new CountableCollection();
echo count($col) . ' ';
foreach ($col as $item) {
    echo $item;
}
Aabcd 4
BError: Countable not implemented correctly
C4 ArrayIterator Object
D4 abcd
Attempts:
2 left
💡 Hint
Countable interface allows count() to work on the object.

Practice

(1/5)
1.

What is the main purpose of the IteratorAggregate interface in PHP?

easy
A. To allow an object to be iterated with foreach by providing an external iterator.
B. To automatically sort arrays inside an object.
C. To enforce type checking on array elements.
D. To convert an object into a string representation.

Solution

  1. Step 1: Understand the role of IteratorAggregate

    The interface requires implementing getIterator() which returns an iterator object.
  2. Step 2: Connect to foreach usage

    This allows the object to be used in foreach loops by providing the iterator externally.
  3. Final Answer:

    To allow an object to be iterated with foreach by providing an external iterator. -> Option A
  4. Quick Check:

    IteratorAggregate enables foreach iteration [OK]
Hint: Remember: IteratorAggregate provides an iterator for foreach [OK]
Common Mistakes:
  • Thinking it sorts data automatically
  • Confusing it with string conversion
  • Assuming it enforces type checks
2.

Which method must a class implement when it uses the IteratorAggregate interface?

easy
A. getItems()
B. iterate()
C. getIterator()
D. toArray()

Solution

  1. Step 1: Recall interface requirements

    The IteratorAggregate interface requires the getIterator() method.
  2. Step 2: Confirm method name

    This method must return an iterator object to enable iteration.
  3. Final Answer:

    getIterator() -> Option C
  4. Quick Check:

    IteratorAggregate requires getIterator() [OK]
Hint: Interface method is always getIterator() [OK]
Common Mistakes:
  • Using iterate() instead of getIterator()
  • Confusing with toArray() method
  • Assuming getItems() is required
3.

What will be the output of this PHP code?

<?php
class MyCollection implements IteratorAggregate {
    private array $items = [1, 2, 3];
    public function getIterator(): Traversable {
        return new ArrayIterator($this->items);
    }
}

$collection = new MyCollection();
foreach ($collection as $item) {
    echo $item . ' ';
}
medium
A. ArrayIterator Object
B. 1 2 3
C. Error: getIterator must return array
D. No output

Solution

  1. Step 1: Understand getIterator() return

    The method returns an ArrayIterator over the array [1, 2, 3].
  2. Step 2: foreach loops over iterator

    The foreach loop iterates over the items 1, 2, and 3, echoing each with a space.
  3. Final Answer:

    1 2 3 -> Option B
  4. Quick Check:

    foreach prints each item from ArrayIterator [OK]
Hint: getIterator returns ArrayIterator to enable foreach [OK]
Common Mistakes:
  • Expecting an error because getIterator returns ArrayIterator
  • Thinking it prints object instead of values
  • Missing the space after each number
4.

Identify the error in this PHP class implementing IteratorAggregate:

<?php
class Numbers implements IteratorAggregate {
    private array $nums = [10, 20, 30];
    public function getIterator() {
        return $this->nums;
    }
}
medium
A. getIterator() must return an object implementing Traversable, not an array.
B. Property $nums should be public, not private.
C. Class must implement Iterator, not IteratorAggregate.
D. getIterator() method must be static.

Solution

  1. Step 1: Check getIterator() return type

    It returns an array, but getIterator() must return an object implementing Traversable.
  2. Step 2: Understand interface contract

    Returning an array causes a type error because arrays do not implement Traversable.
  3. Final Answer:

    getIterator() must return an object implementing Traversable, not an array. -> Option A
  4. Quick Check:

    getIterator() returns Traversable object [OK]
Hint: getIterator must return Traversable object, not array [OK]
Common Mistakes:
  • Returning array directly from getIterator()
  • Thinking private properties cause error here
  • Assuming getIterator() must be static
5.

You want to create a class FilteredCollection that implements IteratorAggregate and only iterates over items greater than 5 from an internal array. Which implementation of getIterator() is correct?

<?php
class FilteredCollection implements IteratorAggregate {
    private array $items;
    public function __construct(array $items) {
        $this->items = $items;
    }
    public function getIterator(): Traversable {
        // Which code below is correct?
    }
}
hard
A. return new ArrayIterator($this->items);
B. return new ArrayIterator(array_map(fn($v) => $v > 5, $this->items));
C. return $this->items;
D. return new ArrayIterator(array_filter($this->items, fn($v) => $v > 5));

Solution

  1. Step 1: Filter items greater than 5

    Use array_filter with a callback to keep only values > 5.
  2. Step 2: Return an ArrayIterator over filtered items

    Wrap filtered array in ArrayIterator to satisfy Traversable return type.
  3. Final Answer:

    return new ArrayIterator(array_filter($this->items, fn($v) => $v > 5)); -> Option D
  4. Quick Check:

    Filter then wrap in ArrayIterator [OK]
Hint: Filter array first, then return ArrayIterator [OK]
Common Mistakes:
  • Returning unfiltered array directly
  • Using array_map instead of array_filter
  • Not wrapping result in an iterator object
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