Skip to content

Instantly share code, notes, and snippets.

@lcherone lcherone/php.md
Created Jan 16, 2018

Embed
What would you like to do?

You can achieve this by using the modulus operator.

<?php
$result = [
    ['id' => 1, 'product_name' => 'a'],  
    ['id' => 2, 'product_name' => 'b'],  
    ['id' => 3, 'product_name' => 'c'],  
    ['id' => 4, 'product_name' => 'd'],  
    ['id' => 5, 'product_name' => 'e'],  
    ['id' => 6, 'product_name' => 'f'],  
    ['id' => 7, 'product_name' => 'g'],  
    ['id' => 8, 'product_name' => 'h'],  
    ['id' => 9, 'product_name' => 'i'],  
    ['id' => 10, 'product_name' => 'j'],  
];
?>
<div class="container">
<?php foreach ($result as $key => $value) {
    if ($key % 3 == 0) { // change 3 to how many items between rows
        if ($key != 0) { echo '</div>'.PHP_EOL; }
        echo '<div class="row">'.PHP_EOL;
    }
    echo '<div class="col s4">'.$value['product_name'].'</div>'.PHP_EOL;
}
?>
  </div>
</div>

https://3v4l.org/vKrf9

Result:

<div class="container">
  <div class="row">
    <div class="col s4">a</div>
    <div class="col s4">b</div>
    <div class="col s4">c</div>
  </div>
  <div class="row">
    <div class="col s4">d</div>
    <div class="col s4">e</div>
    <div class="col s4">f</div>
  </div>
  <div class="row">
    <div class="col s4">g</div>
    <div class="col s4">h</div>
    <div class="col s4">i</div>
  </div>
  <div class="row">
    <div class="col s4">j</div>
  </div>
</div>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.