Skip to content

Instantly share code, notes, and snippets.

@nfreear
Last active July 12, 2021 10:16
Show Gist options
  • Select an option

  • Save nfreear/b4d9f92b3469389a8ca99a111cce7811 to your computer and use it in GitHub Desktop.

Select an option

Save nfreear/b4d9f92b3469389a8ca99a111cce7811 to your computer and use it in GitHub Desktop.
A forward or reverse array iterator, with a test (PHP).
<?php
/**
* A forward or reverse array iterator, with a test (PHP).
*
* @copyright Nick Freear, 12-July-2021.
*
* @see https://doc.wikimedia.org/mediawiki-core/master/php/ReverseArrayIterator_8php_source.html
* @see https://github.com/wikimedia/mediawiki/blob/master/includes/libs/ReverseArrayIterator.php
*/
class ReverseArrayIterator implements Iterator, Countable {
protected $array;
protected $isReverse;
protected $idx;
public function __construct( array $array = [], bool $isReverse = true ) {
if ( is_array( $array ) ) {
$this->array = $array;
} elseif ( is_object( $array ) ) {
$this->array = get_object_vars( $array );
} else {
throw new InvalidArgumentException( __METHOD__ . ' requires an array or object' );
}
$this->isReverse = $isReverse;
$this->rewind();
}
public function current() {
return current( $this->array );
}
public function key(): int | string | null {
return key( $this->array );
}
public function next(): void {
if ($this->isReverse) {
prev( $this->array );
} else {
next( $this->array );
}
$this->idx++;
}
public function rewind(): void {
if ($this->isReverse) {
end( $this->array );
} else {
reset( $this->array );
}
$this->idx = 0;
}
public function valid(): bool {
return key( $this->array ) !== null;
}
public function count(): int {
return count( $this->array );
}
public function index(): int {
return $this->idx;
}
}
/**
* ----------------------------------------------------------
* TEST.
*/
$lastArg = $argv[ $argc - 1 ];
$isReverse = $lastArg === '--reverse';
$programmingLangArray = [ 'Ada', 'Basic', 'C++', 'Delphi', 'E', 'Fortran', 'Go', 'Haskell', 'Javascript' ];
// $programmingLangArray = ["PHP", "C++", "C#", "Python", "Java"];
// $fruitArray = [ 'Apples', 'Bananas', 'Cherries', 'Durian', ];
$arrayIterator = new ReverseArrayIterator($programmingLangArray, $isReverse);
while( $arrayIterator->valid() )
{
echo ($arrayIterator->index() + 1) . '. ' . $arrayIterator->current() . PHP_EOL;
$arrayIterator->next();
}
// End.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment