Another chance to learn how to deal with arrays. Not knowing how to deal with arrays is like trying to count on one finger 🙂
I'll assume you've got all the elements in an array in the right order. Printing them in four columns is giving:
1 2 3 4
5 6 7 8
9
Now, after filling the array, it's just a matter of rearranging its elements before outputting them.
The table rows break the array into chuncks of four elements each. There's a PHP function to do this called [man]array_chunk[/man]. Give it an array and the desired size of a chunk (4 in this case) it will return an array of chunks (which are themselves arrays of elements)
$chunks = array_chunk($array, 4);
The resulting $chunks array is exactly the format of the table above: $chunks[0][0] is 1, $chunks[0][1] is 2, $chunks[1][0] is 5, etc.
Now we want to go through each chunk and reverse them. Funnily enough, PHP has a function called [man]array_reverse[/man]. And it also has [man]foreach[/man] which allows you to do something for each element of an array.
foreach($chunks as $k=>$chunk){
$chunks[$k]=array_reverse($chunk);
}
Now, you could flatten the array back out again (using a foreach loop and [man]array_merge[/man]) and use the code you've already got to print them but the data is already arranged in the same format you want it - $chunks[$i][$j] contains the $jth cell in the $ith row. Why destroy that format only to go to the effort of reconstructing it?
Two nested foreach loops:
<table>
foreach $chunks as $chunk
{ <tr>
foreach $chunk as $element
{ <td>
$element
</td>
}
</tr>
}
</table>
Okay, so the last row might be short a few cells, but I don't think the W3C would have a problem with that. If you do you could use [man]array_pad[/man] on the last element of $chunks after they've all been reversed.