- You can avoid using "counters" if you just declare the key variable in your foreach loop.
- You can avoid multiple conditionals if you leverage the modulus operator (
%
). It divides the first number by the second and outputs the remainder.
- The indices provided by the foreach loop will start from
0
, so the indices that you wish to display as big blocks will include: 0
,1
,6
,7
,12
,and 13
. When $i%6
is applied to these keys, the output will be 0
or 1
.
- Since the only thing that is changing in our echo statement is the class attribute, there is no need to repeat the full
<div>
line. DRY programming practices dictates that you only modify the end of the class value. To accomplish this, I have opted for an inline conditional.
This is the best/simplest way for you to accomplish your desired output.
Code: (Demo)
$myarray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18];
foreach ($myarray as $i=>$v){
echo "<div class=\"cust",($i%6<2?1:2),"\">$v</div>\n";
}
Output:
<div class="cust1">1</div>
<div class="cust1">2</div>
<div class="cust2">3</div>
<div class="cust2">4</div>
<div class="cust2">5</div>
<div class="cust2">6</div>
<div class="cust1">7</div>
<div class="cust1">8</div>
<div class="cust2">9</div>
<div class="cust2">10</div>
<div class="cust2">11</div>
<div class="cust2">12</div>
<div class="cust1">13</div>
<div class="cust1">14</div>
<div class="cust2">15</div>
<div class="cust2">16</div>
<div class="cust2">17</div>
<div class="cust2">18</div>
Alternatively, if you aren't worried about satifying all browsers, you can use a pure css solution with nth-child()
and implode()
.
<style>
div:nth-child(6n+1),div:nth-child(6n+2) {
background: red;
}
</style>
<?php
$myarray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18];
echo '<div>',implode('</div><div>',$myarray),'</div>'; // glue each value with a closing and opening div tag
?>