Here\'s a PHP example of mine. Can anyone find a shorter/easier way to do this?
foreach($posts as $post){?>
You can encapsulate the logic as follows:
<?php
class ListCycler {
private $cols, $offs, $len;
// expects two or more string parameters
public function __construct() {
$this->offs = -1;
$this->len = func_num_args();
$this->cols = func_get_args();
foreach($this->cols as &$c)
$c = trim(strval($c));
}
// the object auto-increments every time it is read
public function __toString() {
$this->offs = ($this->offs+1) % $this->len;
return $this->cols[ $this->offs ];
}
}
?>
<html>
<head>
<style>
ul#posts li.odd { background-color:red; }
ul#posts li.even { background-color:white; }
</style>
</head>
<body>
<div>
<h3>Posts:</h3>
<ul id="posts"><?php
$rc = new ListCycler('odd','even');
foreach($posts as $p)
echo "<li class='$rc'>$p</li>";
?></ul>
</div>
</body>
</html>
<?php $alt = true; foreach ($posts as $post): $alt = !$alt; ?>
<div<?php echo $alt ? ' class="odd"' : ''; ?>>
<!-- Content -->
</div>
<?php endforeach ?>
Would be the simplest and clearest way to do it.
On a side noe, to alternate between two values a and b, a nice way of doing it in a loop is this:
x = a;
while ( true ) {
x = a + b - x;
}
You can also do this without addition and subtraction:
x = a ^ b ^ x;
where ^ is the XOR operation.
If you just want to alternate between 0 and 1, you can do this:
x = 0;
while ( true ) {
x = !x;
}
You could of course use x as an index of colors, CSS style classes and so on.
Fundamentally - no. That's about as easy as it gets. You might rewrite it a bit shorter/cleaner, but the idea will be the same. This is how I would write it:
$c = true; // Let's not forget to initialize our variables, shall we?
foreach($posts as $post)
echo '<div'.(($c = !$c)?' class="odd"':'').">$post</div>";
function row_color($cnt,$even,$odd) {
echo ($cnt%2) ? "<tr bgcolor=\"$odd\">" : "<tr bgcolor=\"$even\">";
}
How to use:
$cnt=0;
while ($row = mysql_fetch_array ($result)) {
row_color($cnt++,"e0e0e0","FFFFFF");
}
Been using something like this:
<?php
function cycle(&$arr) {
$arr[] = array_shift($arr);
return end($arr);
}
$oddEven = array('odd', 'even');
echo cycle($oddEven)."\n";
echo cycle($oddEven)."\n";
echo cycle($oddEven)."\n";