How can the modulo operator be used to achieve alternating background colors in PHP?
To achieve alternating background colors in PHP, we can use the modulo operator (%) to determine if a row is even or odd. By checking if the row number is divisible by 2, we can apply different background colors to alternate rows. This creates a visually appealing effect for tables or lists.
<?php
for ($i = 1; $i <= 10; $i++) {
if ($i % 2 == 0) {
echo '<div style="background-color: #f0f0f0;">Row ' . $i . '</div>';
} else {
echo '<div style="background-color: #ffffff;">Row ' . $i . '</div>';
}
}
?>
Related questions
-
FPDF PHP community
-
concatenation interpolation double quotes
-
regular expression HTML tags filter