Home PHP How to alternate between 2 colors using PHP?
 
 
 

How to alternate between 2 colors using PHP?

PDF Print E-mail

Question: How to alternate between 2 colors using PHP? This could come in handy if you have a table with multiple rows and if you wish to alternate between 2 colors.

 

Answer:

We'll need to use the Modulus Arithmetic Operator for this (%). Modulus (%) gets the remainder after a division has been made between 2 numbers. eg. 3%2 = 1

Code Example:

 
 <table border="0" cellpadding="2" cellspacing="4">
<?php
   $rows = 10; //Number of rows
    for($i=0;$i<$rows;$i++){ //Looping through rows
        $a = $i % 2; //Modulus Calculation
        
        if($a == 1){ //If remainder is one we select grey as the color
            $color = "#3e3e3e";
        }else{ //If there's no remainder the color will be white
            $color = "#ffffff"; 
        }
        ?>
        <tr style="background-color:<?=$color?>"> //Applying the relevant color
            <td>Color 1</td>
        </tr>
        <?php
    }
?>
</table>
 

Output:

Color 1
Color 1
Color 1
Color 1
Color 1
Color 1
Color 1
Color 1
Color 1
Color 1

+/-
+/- Write comment
Your Contact Details:
Comment:
[b] [i] [u] [url] [quote] [code] [img]   
Security Please input the anti-spam code that you can read in the image.
 

Go Daddy $7.49 .com Sale!