tags:

views:

66

answers:

4

I am trying to print an 8x8 grid on php can anyone check this code is I am doing something wrong

      $row = 0;
  $col = 0;

   print "<form>";
  while ($row <= 8){
      print "<tr>";
   $row++;

     while ($col <= 8){
    print "<td>"; 
    print "<input type="checkbox" name="battle" value="ships">";
    print "</td>";
    $col++;

  }


  print "</tr>";
   )
   print "</form>";
A: 

Use while($row < 8) and while($col < 8) (instead of <=) or else you will be printing a 9x9 table.

Use single quotes for checkbox, battle, and ships. The outside quotation marks will treat the expression as "<input type=" , checkbox, " name=", battle, " value=", ships, ">" (a syntax error) if you use double quotes on the inside.

For syntax problems, it helps to use an IDE - a good one in the browser would be ideone.com. You can enable syntax highlighting.

irrelephant
A: 

Several issues.. a couple stick out:

You're using the condition $col <= 8. This will iterate 9 times if your value starts at 0, because 0 through 8 is 9 numbers. When working with base 0 and counting up finitely, always use just < (less than) your max as that basically makes your ending number one less, making up for the 0 base.

Your last closing parenthesis should be a closing brace. You start the while with a {, so you need to finish it with a }, not ).

Gavin
+2  A: 
$out = "<tr>";
for($i = 0; $i < 8*8; $i++){

    if($i && $i % 8 == 0)
        $out .= "</tr><tr>";

    $out .= "<td>..</td>";
}
$out .= "</tr>";

echo $out;
Alfonso de la Osa
@hgbso you made a performance mistake on using print, I made it using double quotes
Alfonso de la Osa
This is a more "clever" solution, for this particular use case. It forgoes the clarity of code in using two loops (I would've used nested for loops, myself) to gain better performance. It doesn't answer the most fundamental issues of the question, but it's a good exercise in thinking about the problem to find ways to do it better.
Visionary Software Solutions
+1  A: 

Few mistakes. Right code should be following:

$row = 0;
print "<form>";
print "<table>";
while ($row < 8){ // Counts to 8. (from 0...7 = 8 times. 0 ... 8 = 9 times)
   print "<tr>";
   $row++;
   $col = 0; // reset column to 0 each time printing one row.

   while ($col < 8){
    print "<td>"; 
    print "<input type=\"checkbox\" name=\"battle\" value=\"ships\">"; 
     // Add \ before " otherwise it will treat as the end of the quote.
    print "</td>";
    $col++;
   }

   print "</tr>";
}
print "</table>";
print "</form>";

Hope this helps.

tanjir
This would be an excellent candidate for a `for` loop or two....
cHao
The same thing can be done with one while loop. Instead of giving him just "code", I tried to explain where did he make mistake.
tanjir