You program a "</tr>" and a "<tr>" into the loop every 5 iterations.
The Modulus operator is what you'd need. Inside your "for" loop:
if (($i%5)==0) {
echo "</tr><tr><td>";
// or whatever exactly is needed for formatting...
The expression ($i%5) determines the remainder when $i is divided by 5. If it's zero, then we know that the image count is 5, 10, 15, etc.......