PHP

How to alternate between 2 colors using PHP

Written by Ian Carnaghan · 27 sec read >

This could come in handy if you have a table with multiple rows and if you wish to alternate between 2 colors.

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>

Last Updated On March 22, 2018
Written by Ian Carnaghan
I am a software developer and online educator who likes to keep up with all the latest in technology. I also manage cloud infrastructure, continuous monitoring, DevOps processes, security, and continuous integration and deployment. In my spare time I teach undergraduate classes in web development. Profile

Leave a Reply

avatar
  Subscribe  
Notify of