Complete the code to start the iterator at the first element.
<?php class MyIterator implements Iterator { private array $items = [1, 2, 3]; private int $position = 0; public function rewind(): void { $this->position = [1]; } public function current(): mixed { return $this->items[$this->position]; } public function key(): int { return $this->position; } public function next(): void { $this->position++; } public function valid(): bool { return isset($this->items[$this->position]); } } ?>
The rewind() method resets the iterator position to the first element, which is index 0.
Complete the code to check if the current position is valid.
<?php
public function valid(): bool {
return [1]($this->items[$this->position]);
}
empty() returns false for zero or empty strings, which may be valid elements.is_null() checks value, not existence.array_key_exists() requires the key, but here we check the value.The isset() function checks if the current position exists in the array, ensuring the iterator is valid.
Fix the error in the next() method to correctly advance the iterator.
<?php
public function next(): void {
$this->position [1];
}
-- moves backward, causing incorrect iteration.+= without a value is invalid syntax.The next() method should increase the position by one using ++ to move forward.
Fill both blanks to implement the current() method returning the current item.
<?php
public function current(): mixed {
return $this->items[1];
}
->position instead of array index.The current() method returns the element at the current position using array access syntax with [$this->position].
Fill all three blanks to complete the Iterator class with correct methods.
<?php class MyIterator implements Iterator { private array $items = [10, 20, 30]; private int $position = 0; public function rewind(): void { $this->position = [1]; } public function current(): mixed { return $this->items[2]; } public function valid(): bool { return [3]($this->items[$this->position]); } } ?>
empty() or is_null() instead of isset().The rewind() method sets position to 0, current() returns the item at current position using square brackets, and valid() checks if the position exists using isset().