Wrapping Ivs with a class inside a repeat loop

Asked

Viewed 38 times

0

I have the following php code

for ($i = 0; $i <6; $i++){
    echo '<div class="item">';
    echo $i;
    echo '</div>';
    }
?>

I would like class until position 3 to be involved by a div, and the two remaining classes to be involved by another class, so that the final result is this below:

<div class="coluna-1">
    <div class="item">0</div>
    <div class="item">1</div>
    <div class="item">2</div>
    <div class="item">3</div>
</div>
<div class="coluna-2">
    <div class="item">4</div>
    <div class="item">5</div>
</div>

I made several attempts, but could not, the way I was doing was printing one element inside the other.

1 answer

2


You can create a function and call twice:

<?php

function colunaDiv($className, $primeiro, $ultimo) {
    echo '<div class="'.$className.'">';

    for($i = $primeiro; $i <= $ultimo; $i++) {
        echo '<div class="item">';
        echo $i;
        echo '</div>';
    }

    echo '</div>';
}

colunaDiv("coluna-1", 0, 4);
colunaDiv("coluna-2", 5, 6);

?>
  • Thank you very much Daniel, it worked super well, I only had to pass two more parameters that I had in the code and it was show

Browser other questions tagged

You are not signed in. Login or sign up in order to post.