PHP AJAX handler to fill an HTML table
Trying to follow your mathematical loop conditions makes my eyes go crossed in a hurry.

Perhaps you'd entertain a less-math-heavy alternative:

foreach (array_chunk($array, 4) as $row) {
    echo '&lt;tr&gt;&lt;td&gt;' , implode('&lt;/td&gt;&lt;td&gt;', $row) , '&lt;/td&gt;' , str_repeat('&lt;td&gt;&lt;/td&gt;', 4-count($row)) , '&lt;/tr&gt;';
}


Granted this will be making a no-output call of str_repeat() on all rows except potentially the final row, but I think this technique will be more developer friendly.  I'm assuming that I understand your $data (Demo).  I could have written a conditional for str_repeat() but felt that would only bloat the code.

I tend to lean toward passing json back from an ajax call, but for this situation sending back html is the simpler approach.