How to iterate through a collection of items and display them organised in a matrix with modulo operator

lets say you want to display a collection of items organised in rows and columns, and you do not want to use tables, and rather want to go with a tableless design.

This is the result you are aiming at:

<div class="row>
  <div class="item>item 1</div>
  <div class="item>item 2</div>
  <div class="item>item 3</div>
</div><!-- end row -->
<div class="row>
  <div class="item>item 4</div>
  <div class="item>item 5</div>
  <div class="item>item 6</div>
</div><!-- end row -->
<div class="row>
  <div class="item>item 7</div>
  <div class="item>item 8</div>
  <div class="item>item 9</div>
</div><!-- end row -->

A good way to do it would be to use the modulo operator. In PHP, you can put a counter and use the counter to change line using the modulo operator. If you want to have 3 items in the row, do $n%3, when $n%3 == 1 that means you should start a row, when $n%3 == 0 it means you should close the row. This asumes that $n is initiated with 1.

In ruby, it is the division modulo operator is %


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s