Foreach - display diff bgcolor

Is there a way to change the background color on each row displayed using a foreach statement. I’ve tried to add an if statement at the end of this to change the color but it does not work. Am I using the foreach incorrectly?

my example
echo “\n

\n”;
echo “\n”;
echo “\n
” .
"\n
" .
"\n
" .
"\n
" .
"\n
" .
"\n
" .
"\n
";

$currbackcolor = “silver”;
While ($row = @ mysql_fetch_row($result))
{
echo “\n

”;
foreach($row as $data)
echo "\n\t";
echo “\n”;

// Add If statement to change back colour

If ($currbackcolor = “silver”)
$newbackcolor = “blue”;
else
$newbackcolor “silver”;
}

Echo “\n

CodeFirst NameLast NameHome PhoneBus. PhoneName
<font color=“white”> $data
\n”;

What I usually do in such a case is something like this:

…snip…

while ($row = mysql_fetch_array($result)) {
if ($alternated == NO || $alternated == “”) {
$alternated = YES;
$td_bgcolor = ‘#CCCCCC’;
} else {
$alternated = NO;
$td_bgcolor = ‘#AAAAAA’;
}

print “

” . $row[0] . “”;
}

…snip…

I don’t know if this is the most efficient or best way to go about it, but it seems to run pretty efficiently and does the job for me.

  • Jeff @ DreamHost
  • DH Discussion Forum Admin

Thx Jeff. Your suggestion works fine for me right now. I’m wondering if what I was trying to does not work in the “Foreach” statement. Regardless, you’ve given me a good workable solution and I’m moving forward up the learning ramp of php. Standby for the next question…

Ucurl
WM for UnionvilleCurlingClub.com

Your mistake was pretty simple…you were never really changing $currbackcolor. change both the $newbackcolor’s to be $currbackcolor and it’ll work.

nate.

Thanks Nate,
Actually, When I cut and pasted in my example, I forgot a line from my original code… after the If statement.

$currbackcolor = $newbackcolor;

and it still didn’t work. (Actually it worked once on the first and second record.) Thats why I thought it was something specific to the foreach statement.