Hi, I'm a bit of a newb and have just started studying PHP. I have a simple task to do but just can't find the info I need. The task is: Write a function grid ($x, $y) which prints out <table> in with size $x rows by $y columns with a unique number printed in every cell. Pleeease help!!! Thanks.
You have a number of ways you can do this. It will be a nested loop that you need. while, for.. Personally I would do a nested for loop. Print one table row then print the next table row. function grid ($numx, $numy){ $var = 0; echo '<table>'; for($y=0;$y <= $numy; $y++;) { echo "<tr>"; for($x=0;$x <= $numx; $x++;) { $var++; echo "<td>$var</td>"; } echo "</tr>"; } echo '</table>'; } PHP:
Exodus, thanks very much for your help. I added a couple of things to make a border around each cell and also to try and set the size of the grid at two columns and three rows. <?php function grid ($numx, $numy){ $var = 0; echo '<table border="1">'; for($y=0;$y <= $numy; $y++) { echo "<tr>"; for($x=0;$x <= $numx; $x++) { $var++; echo "<td>$var</td>"; } echo "</tr>"; } echo '</table>'; } grid(3,2); ?> However, the print out gives me 3 rows and four columns. Can you explain why this is, please? Thanks again.
doh.. $x=0, $y=0.. Change those to $x=1, $y=1 The basic idea is there though. Play around with it to figure out what a for loop does.