How can a counter be used to determine when to end a row and start a new one in a table in PHP?

To determine when to end a row and start a new one in a table in PHP, you can use a counter variable that increments with each iteration of the loop that generates table cells. Once the counter reaches a certain threshold (e.g. the number of columns in each row), you can close the current row and start a new one. This ensures that the table structure is maintained correctly.

<?php
// Example code to generate a table with 3 columns
$totalColumns = 3;
$data = ['Cell 1', 'Cell 2', 'Cell 3', 'Cell 4', 'Cell 5', 'Cell 6'];

echo '<table>';
$counter = 0;
foreach($data as $cell) {
    if($counter % $totalColumns == 0) {
        echo '<tr>';
    }
    
    echo '<td>' . $cell . '</td>';
    
    $counter++;
    
    if($counter % $totalColumns == 0) {
        echo '</tr>';
    }
}

// Close any remaining row
if($counter % $totalColumns != 0) {
    echo '</tr>';
}

echo '</table>';
?>