foreach - display diff bgcolor

foreach - display diff bgcolor

Posted by: ucurl
Posted on: 2002-10-15 18:17:00

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<Table border=0 valign=top align=center><font face=Arial size=1>n";
echo "n<b><tr>";
echo "n<th>Code</th>" .
"n<th>First Name</th>" .
"n<th>Last Name</th>" .
"n<th>Home Phone</th>" .
"n<th>Bus. Phone</th>" .
"n<th>Name</th>" .
"n</tr></b>";

$currbackcolor = "silver";
While ($row = @ mysql_fetch_row($result))
{
echo "n<tr>";
foreach($row as $data)
echo "nt<td bgcolor=$currbackcolour><b><font color="white"> $data </b></td>";
echo "n</tr>";

// Add If statement to change back colour

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

Echo "n</Table>n";


Re: foreach - display diff bgcolor

Posted by: Jeff @ DreamHost
Posted on: 2002-10-15 18:38:00

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 "<tr><td bgcolor='$td_bgcolor'>" . $row[0] . "</td></tr>";
}
# ...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

Re: foreach - display diff bgcolor

Posted by: ucurl
Posted on: 2002-10-16 07:09:00

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

Re: foreach - display diff bgcolor

Posted by: nate
Posted on: 2002-10-16 12:00:00

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

nate.

In reply to:



// Add If statement to change back colour

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



Re: foreach - display diff bgcolor

Posted by: ucurl
Posted on: 2002-10-16 12:25:00

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.

Tags: foreachbackground colorechoadd