Forum Moderators: coopster

Message Too Old, No Replies

Alternating Row Color Using modulo

         

nxfx

5:56 am on Jul 8, 2006 (gmt 0)

10+ Year Member



Hello

currently i am using:

if($i % 2 == 0 ){
$color="row1";
}else{
$color="row2";
}
$i++;

in my foreach loops, is there a Handy function i vould use instead, i have been trying but so far no luck!

Thank you

the_nerd

11:29 am on Jul 8, 2006 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Hi,
you can either use an array, like this:

$color[0] = "row1";
$color[1] = "row2";

$a = 4;
echo $color[$a%2] . "<br>";
$a = 3;
echo $color[$a%2] . "<br>";

or define your own little function:

function color ($c1, $c2, $index) {
if ($index%2 == 0)
return ($c1);
else
return ($c2);
}

echo color ("row1", "row2", 4) . "<br>";
echo color ("row1", "row2", 3) . "<br>";

have fun,

nerd

dreamcatcher

11:29 am on Jul 8, 2006 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Hi nxfx,

I usually check for an integer with the count in the loop:


$count = 0;

foreach ($blah as $something)
{

if (is_int($count++/2))
{
$color="row1";
}else{
$color="row2";
}

}

Something simple like that should work ok. So, each time the count increments, the division will be an integer, then it won`t, then it will...etc

dc

the_nerd

11:41 am on Jul 8, 2006 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



sorry, I didn't read the foreach-part.

$color[0] = "row1";
$color[1] = "row2";
$i = 0;

foreach ( ..... ) {
echo $color [$i%2];
$i++
}

or simply

$i = 0;
foreach ( ..... ) {
echo ($i%2==0)? "row1" : "row2";
$i++
}

but those ternary operator are hard to read if you look at the code later.

nxfx

12:11 am on Jul 9, 2006 (gmt 0)

10+ Year Member



Thank you,

the function worked perfect.

Benjamin