Optimizing code for foreach
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;