Jump to content

[SOLVED] Change background COLOR for a TABLE ROW


AndieB

Recommended Posts

Hi all!

 

This has most likely been asked tons of times before, but when I did a search, so much more appear, so it felt easier to write a NEW topic.

 

I'm letting my PHP script echo out a TABLE with rows and cells, reading rows from a database. Now, if I want the background color to change in a very effective PHP script way, during the while syntax that draws up the rows in the table, how do I manage this in a very code effective way?

 

Let's say that $bgcolor = "#445566";

and it should switch to value "#667788" on every other row, then back again... it would look something like this:

 

echo "<tr style=\"background-color: " . $bgcolor . ";\" >text text text</tr >";

 

I've seen a very long time back ago, a solution in just one row of code... don't know if :: were used or something like that.

 

Anyway... anyone has some ideas?

 

Thank you all in advance!

 

--Andreas

you use the % for that to make it easy and a counter var in this case $i

if you use a while loop you will need to place $i++ in it

<?php
for($i=0;$i<10;$i++){
//shorthand if statement
        $bgcolor=($i%2)?"lightcolor":"darkcolor";
echo $bgcolor."<br />";
}
?>

One way of doing this:

<?php
$bgcolor = "#445566";
for ($i=0;$i<15;$i++) { //or your loop control here
   $bgcolor = ($bgcolor == "#445566")?"#667788":"#445566";
   echo "<tr style=\"background-color: " . $bgcolor . ";\" >text text text</tr >";
} ?>

 

Ken

One way of doing this:

<?php
$bgcolor = "#445566";
for ($i=0;$i<15;$i++) { //or your loop control here
   $bgcolor = ($bgcolor == "#445566")?"#667788":"#445566";
   echo "<tr style=\"background-color: " . $bgcolor . ";\" >text text text</tr >";
} ?>

 

Ken

 

Hi Ken!!

 

Thank you very much!

Now I recognize the row that I was talking about:

$bgcolor = ($bgcolor == "#445566")?"#667788":"#445566";

 

What is this called when you use a ? character and a : ??

It somehow switches the values, right?

 

Again, thank you very much!

 

Sincerely,

 

Andreas

 

$bgcolor = ($bgcolor == "#445566")?"#667788":"#445566";

What is this called when you use a ? character and a : ??

It somehow switches the values, right?

 

 

You are correct it switches the value. It is a short way to notate a if else. Using this syntax is called shorthand.

 

this:

$bgcolor = ($bgcolor == "#445566")?"#667788":"#445566";

 

equals:


if($bgcolor == "#445566"){
    $bgcolor="#667788";
}else{
    $bgcolor="#445566";
}

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.