Cycling between strings, a novel implementation
Posted on April 5th, 2004 in Code Repository | 4 Comments »
When outputting a table, a common task is to alternate the row colours to give a zebra effect – an effect commonly said (though debated) to increase readability.
A novel solution to this problem involves using PHP5’s new __toString method: introducing Cycle.
/**
* A simple cycle class for alternating between strings.
*
* @author Aidan Lister <aidan@php.net>
* @version 1.0.1
* @link http://aidanlister.com/repos/v/Cycle.php
*/
class Cycle
{
/**
* Array of strings to be cycled
*
* @var array
*/
private $_args;
/**
* The current position in the stack
*
* @var array
*/
private $_key;
/**
* Constructor
*
* @param overloader Strings to be cycled through
*/
function __construct()
{
$this->_args = func_get_args();
$this->_key = -1;
}
/**
* Convert to a string
*
* @return string The next string in the stack
*/
function __toString()
{
return (string) isset($this->_args[$this->_key += 1]) ?
$this->_args[$this->_key] :
$this->_args[$this->_key = 0] ;
}
}
Thus with minimal effort, simply echoing the string will seemingly magically alternate between the specified outputs. An example:
require_once 'Cycle.php';
$rowclass = new Cycle('odd', 'even');
for ($i = 0; $i < 5; $i++) {
echo "<td class=$rowclass>\n";
}
This would output:
<td class=odd> <td class=even> <td class=odd> <td class=even>
And there we have it, zebra striped tables without a messy counter or other tricks.
4 Responses
Wow, at first I was wondering what in the world this could be used for. But now that I thought about it, it can be very useful. Thanks aidan.
very nice script.. i always made this with a function and a global var
but this way is more comfortable
although of more limited use, i accomplished similar functionality using just a function.
<?php
function cycle($array = array()) {
static $index, $nodes;
if ($nodes !== $array && count($array)) {
$nodes = $array;
$index = -1;
}
$index++;
if (!isset($nodes[$index])) {
$index = 0;
}
return $nodes[$index];
}
?>
[...] Aidan Lister’s page I cam across a very interesting piece of code that cycles between strings. You instantiate the class with the values to cycle through given to the constructor. Now from here [...]