Skip to content

Instantly share code, notes, and snippets.

@ojhaujjwal
Last active March 12, 2020 23:44
Show Gist options
  • Save ojhaujjwal/614c130096c9bb9d2a7d6e953ce20de2 to your computer and use it in GitHub Desktop.
Save ojhaujjwal/614c130096c9bb9d2a7d6e953ce20de2 to your computer and use it in GitHub Desktop.
<?php
class FileIterator implements \Iterator {
protected $filePointer;
protected $data;
protected $key;
public function __construct($file) {
$this->filePointer = fopen($file, 'rb');
if (!$this->filePointer) {
throw new \Exception('File could not be opened');
};
}
public function __destruct() {
fclose($this->filePointer);
}
public function current() {
return $this->data;
}
public function key() {
return $this->key;
}
public function next(): void {
$this->data = fgets($this->filePointer);
$this->key++;
}
public function rewind(): void {
fseek($this->filePointer, 0);
$this->data = fgets($this->filePointer);
$this->key = 0;
}
public function valid(): bool {
return false !== $this->data;
}
}
$lines = new FileIterator('/path-to-file');
foreach ($lines as $line) {
echo $line. "\n";
}
@ojhaujjwal
Copy link
Author

ojhaujjwal commented Mar 12, 2020

good question @geshan. At the start, rewind is called, where the key is set to 0.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment