Search code examples
phpline-breaksmodulo

PHP: <div> linebreak with modulo operator


My PHP code looks like this and produces this line breaking (Bootstrap) output.

$i = 0;
foreach ($p as $product) {
    if ($i % 3 == 0) {
        echo '<div class="row">';
    }
    echo 'something';
    if ($i % 3 == 2) {
        echo '</div>';
    }
    $i++;
}

How to catch up the last missing HTML-div to fix the footer?


Solution

  • You should close the div also when the $i-th product is the last one:

    $i = 0;
    foreach ($p as $product) {
        if ($i % 3 == 0) {
            echo '<div class="row">';
        }
        echo 'something';
        if ($i % 3 == 2 || $i == sizeof($p) - 1) {
            echo '</div>';
        }
        $i++;
    }