Skip to content

Instantly share code, notes, and snippets.

@saltandvinegarcrisps
Last active October 25, 2016 16:16
Show Gist options
  • Save saltandvinegarcrisps/4140442 to your computer and use it in GitHub Desktop.
Save saltandvinegarcrisps/4140442 to your computer and use it in GitHub Desktop.
Alternator Class - useful for alternating colours or other linear recurrencing items
<?php
class Alternator {
// The values that are to be alternated.
private $values = array();
// Count of the array, used to increase performance.
private $count = 0;
// The current index. Starts as -1 so the first index will be 0.
private $cur = -1;
// Creates new instances of the Alternator.
public function __construct($values) {
$this->values = $values;
$this->count = count($values);
}
// Gets the next value in the rotation.
public function go() {
return $this->values[$this->cur = ++$this->cur % $this->count];
}
// Resets the Alternator
public function reset() {
$this->cur = 0;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment