Optimizing code for foreach I need to HTML table output like:

&lt;table&gt;
&lt;tr&gt;
    &lt;td&gt;ITEM&lt;td&gt;
    &lt;td&gt;ITEM&lt;td&gt;
    &lt;td&gt;ITEM&lt;td&gt;
&lt;/tr&gt;
&lt;/table&gt;

&lt;table&gt;
&lt;tr&gt;
    &lt;td&gt;ITEM&lt;td&gt;
    &lt;td&gt;ITEM&lt;td&gt;
    &lt;td&gt;ITEM&lt;td&gt;
&lt;/tr&gt;
&lt;/table&gt;

&lt;table&gt;
&lt;tr&gt;
    &lt;td&gt;ITEM&lt;td&gt;
    &lt;td&gt;ITEM&lt;td&gt;
    &lt;td&gt;ITEM&lt;td&gt;
&lt;/tr&gt;
&lt;/table&gt;


My code before:

&lt;?php $i = 1;?&gt;
&lt;?php foreach ($items as $item): ?&gt;
&lt;?php if ($i == 1 || $i == 4 || $i == 7 ......): ?&gt;&lt;table&gt;&lt;tr&gt;&lt;?php endif; ?&gt;
    &lt;td&gt; CONTENT &lt;/td&gt;
&lt;?php if ($i == 3 || $i == 6 || $i == 9 ......):?&gt;&lt;/table&gt;&lt;/tr&gt;&lt;?php endif;?&gt;
&lt;?php $i++ ?&gt;                                                           
&lt;?php endforeach; ?&gt;


My code now:

&lt;?php $i = 1;?&gt;
&lt;?php foreach ($items as $item): ?&gt;
&lt;?php if ($i % 3 == 1): ?&gt;&lt;table&gt;&lt;tr&gt;&lt;?php endif; ?&gt;
    &lt;td&gt; CONTENT &lt;/td&gt;
&lt;?php if ($i % 3 == 0):?&gt;&lt;/table&gt;&lt;/tr&gt;&lt;?php endif;?&gt;
&lt;?php $i++ ?&gt;                                                           
&lt;?php endforeach; ?&gt;
I assume the $items array is indexed by numbers, otherwise you have to change the code below to include a counter.

foreach ($items as $i =&gt; $item) {
    if ($i % 3 == 0) {
        // Do something for 0, 3, 6, 9, ...
    } elseif ($i % 3 == 1) {
        // Do something for 1, 4, 7, 10, ...
    } elseif ($i % 3 == 2) {
        // Do something for 2, 5, 8, 11, ...
    }
}


This code uses the modulo operator %.

After your edit
The following code is a more clear solution to your problem:

foreach (array_chunk($items, 3) as $chunk):
    echo '&lt;table&gt;&lt;tr&gt;';
    foreach ($chunk as $item):
        echo '&lt;td&gt;' . $item . '&lt;/td&gt;';
    endforeach;
    echo '&lt;/tr&gt;&lt;/table&gt;';
endforeach;