0

Is there a way to create multiple rows of thirds using w3.css and a foreach loop also to populate the thirds with data from a sample database?

Tried using but this would create multiple thirds in a single row instead:

<?php foreach ($products as $index => $product) :?>

    <div class="w3-row">
<?php foreach ($products as $index => $product) : ?>
      <div class="w3-third w3-container">
        <h2>product 1 </h2>
      </div>
    </div>
    <?php endforeach; ?>
</div>
<?php endforeach; ?>

Expected output:

<div class="w3-row">
  <div class="w3-third w3-container">
    <h2>Item 1 from a database</h2>
  </div>
  <div class="w3-third w3-container">
    <h2>Item 2 from a database</h2>
  </div>
  <div class="w3-third w3-container">
    <h2>Item 3 from a database</h2>
  </div>
</div>

<div class="w3-row">
      <div class="w3-third w3-container">
        <h2>Item 4 from a database</h2>
      </div>
      <div class="w3-third w3-container">
        <h2>Item 5 from a database</h2>
      </div>
      <div class="w3-third w3-container">
        <h2>Item 6 from a database</h2>
      </div>
    </div>

2 Answers2

1

so you want to get a row for every third element of the loop. You can achieve this by checking how many of them should be in a row with modulo.

<?php foreach ($products as $index => $product): $aThird = ($index+1%3)===0; ?>
    <?php if ($aThird): ?>
        <div class="w3-row">
    <?php endif ?>
      <div class="w3-third w3-container">
        <h2>product 1 </h2>
      </div>
    <?php if ($aThird): ?>
        </div>
    <?php endif ?>
</div>
<?php endforeach; ?>

But my I would strongly suggest to look at grid layout https://css-tricks.com/snippets/css/complete-guide-grid/

bro
  • 61
  • 6
  • For true work it's better to change `$aThird = ($index+1%3)===0;` to `$aThird = ($index % 3) == 0;`. because array indexes start from zero and you need to add `
    ` for first `w3-third`.
    – Amirreza Noori Dec 11 '21 at 08:03
0

You can use array_chunk() function. It splits an array into chunks of new arrays

$myArray = ['Item-1', 'Item-2', 'Item-3', 'Item-4', 'Item-5', 'Item-6'];

$myArray = array_chunk($myArray, 3);

foreach($myArray as $Array){

     echo '<div class="w3-row">';
     
     foreach($Array as $Value){
          echo '<div class="w3-third w3-container">'.$Value.'</div>';
     }

     echo '</div>';

}
virtualize
  • 2,287
  • 2
  • 25
  • 36
abhiseka
  • 1
  • 1