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
  • Please show us the PHP you have tried so far. Commented Nov 29, 2021 at 18:08
  • Thanks ive updated the post, not sure if its clear enough for what I'm trying to achieve Commented Nov 29, 2021 at 18:15

2 Answers 2

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/

Sign up to request clarification or add additional context in comments.

1 Comment

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 <div class="w3-row"> for first w3-third.
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>';

}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.