Did you see my later comments? You can do this with checking if index%3 for three columns or index%2 for 2 columns, you wouldn't need this logic