index/src/ArrayIterator.php
2023-11-09 13:12:34 +00:00

65 lines
1.3 KiB
PHP

<?php
// ArrayIterator.php
// Created: 2022-02-03
// Updated: 2023-11-09
namespace Index;
use Iterator;
/**
* Provides an Iterator implementation for normal arrays.
*/
class ArrayIterator implements Iterator {
private array $array;
private bool $wasValid = true;
/**
* @param array $array Array to iterate upon.
*/
public function __construct(array $array) {
$this->array = $array;
}
/**
* Returns the current element.
*
* @return mixed Can return any type.
*/
public function current(): mixed {
return current($this->array);
}
/**
* Returns the key of the current element.
*
* @return mixed Returns scalar on success, or null on failure.
*/
public function key(): mixed {
return key($this->array);
}
/**
* Moves forward to next element.
*/
public function next(): void {
$this->wasValid = next($this->array) !== false;
}
/**
* Rewind the Iterator to the first element.
*/
public function rewind(): void {
$this->wasValid = reset($this->array) !== false;
}
/**
* Checks if current position is valid.
*
* @return bool Returns true on success or false on failure.
*/
public function valid(): bool {
return $this->wasValid;
}
}