How can the Modulo Operator be applied in a loop to control the output of table rows in PHP?
When outputting table rows in a loop in PHP, you can use the modulo operator (%) to control the number of columns per row. By using the modulo operator with a specific number (e.g. 3 for 3 columns per row), you can determine when to start a new row in the table.
<?php
$rows = 10;
$columns_per_row = 3;
echo '<table>';
for ($i = 1; $i <= $rows; $i++) {
if (($i - 1) % $columns_per_row == 0) {
echo '<tr>';
}
echo '<td>Row ' . $i . '</td>';
if ($i % $columns_per_row == 0 || $i == $rows) {
echo '</tr>';
}
}
echo '</table>';
?>
Keywords
Related Questions
- What PHP functions can be used to format numbers with commas for display purposes?
- What are the best practices for defining character encoding in PHP scripts to ensure proper form data submission and processing?
- What are the limitations of styling buttons on a webpage using CSS in the Mobile Internet Explorer on a PocketPC?