开发者

PHP Looping 3 background colours in while loop

I'm showing data from a db table and I can loop through 2 background colours pretty easily, but how can I expand that to incorporate 3 or possibly 4 back开发者_开发知识库ground colours??

Currently I have this code for the two css classes:

php echo $i++ % 2 ? 'class="even"' : 'class="odd"';

Many thanks


Use an array of classes and use the result of the modulo (remainder) as your index.

$classes = array("odd", "even", "odder", "more_even");
for ($i=0; $i < 10; $i++)
{
    echo $classes[$i%4];
}

You can then replace the 4 with the size of the array to make it completely dynamic based on the array.

echo "<br>".$classes[$i%count($classes)];


The easiest way I can think is to incorperate a switch statement:

switch($i % 3)
{
    case 0: echo 'class="even"'; break;
    case 1: echo 'class="odd"'; break;
    case 2: echo 'class="..."'; break;
}

Ok, mine is just verbose haha


This is the same as @Gazler's approach. However, I'm using a while-loop, since you're talking about a db-table (probably MySQL?).

$result = mysql_query($query);
$i = -1;
while ($row = mysql_fetch_array($result)) {
    echo (($i++) % 2) ? 'odd' : 'even';
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜