Separate and Group MySQL output using PHP

Hi

I have a mysql query which delivers a result set which can be variable in the number or rows using php. What I need to do is if the total is divisible by 5 then create tables of 5 rows in each, separated. I.e 20 rows would result in 4 tables of 5. However if the result set is not divisible by 5, I need to calculate a minimum of 4 rows per table.. I.e if the result set is 21, then the output would be 1 table of 5 and 4 tables of 4 rows. The basics need to be to total the result rows and calculate the best match by 5 with a minimum in each of 4 rows?

Can anyone help with this.