Using the Modulus PHP Arithmetic Operator, you can easily assign an alternate class to a repeated element. Depending on whether a number is odd or even, you could choose which color to make each row by assigning the css style selector to the repeated tag.
Example PHP Function
This function will output the text string “ alt“. It is best used inside the class attribute of your HTML element if the number passed to this function is an even number.
function doAlt($n) {
if ($n % 2) {
echo(' alt');
}
}
Example HTML Markup
for ($i = 0; $i <= 4; $i++) {
echo '<div class="row'.doAlt($i).'">Row '.$i.'</div>';
}
Example CSS Styles
.row {
background-color:#000000;
color:#FFFFFF;
width:300px;
}
.alt {
background-color:#1B2426;
}
Example Output
<div class="row">Row 0</div> <div class="row alt">Row 1</div> <div class="row">Row 2</div> <div class="row alt">Row 3</div> <div class="row">Row 4</div>