Cycling Between Strings
A common programming challenge: cycling through multiple values repeatedly. Think alternating row colors in a table, or rotating through a set of CSS classes.
The standard implementation I’ve seen is to define a variable, count it up to a maximum, then reset:
$colors = ['odd', 'even'];
$index = 0;
foreach ($rows as $row) {
echo '<tr class="' . $colors[$index] . '">';
$index = ($index + 1) % count($colors);
// ...
}
It works, but it’s clunky. You’re managing state manually.
A Cleaner Approach
Using object-oriented design, we can encapsulate the cycling logic in a class:
class Cycle
{
private $values;
private $index = 0;
public function __construct(...$values)
{
$this->values = $values;
}
public function __toString()
{
$value = $this->values[$this->index];
$this->index = ($this->index + 1) % count($this->values);
return $value;
}
}
Now the usage becomes beautifully simple:
$cycle = new Cycle('odd', 'even');
foreach ($rows as $row) {
echo '<tr class="' . $cycle . '">';
// ...
}
Through PHP’s __toString() magic method, the object automatically returns the current value and advances the pointer, wrapping around when necessary.
This pattern, inspired by Aidan Lister’s implementation, is very simple yet powerful. It demonstrates how thoughtful class design can provide cleaner, more maintainable code for problems that might otherwise require awkward procedural solutions.
The approach isn’t limited to strings either—the same concept works for any values you need to cycle through.