user4177540
user4177540

Reputation:

Dynamic Table Continuous <td> Count

I am stuck in a weird problem, I want to show the continuous number till the last in the row and cols, instead of that its showing form 1-50 and then again the row starts with 1 up-to 50.

<?php
  $rows = 10;
  $cols = 50;
  $x=1 ;
  echo "<table border='1'>"; 
  for($tr=1;$tr<=$rows;$tr++){

     echo "<tr>";

    for($td=1;$td<=$cols;$td++){
           echo "<td>$td</td>";
    }
       echo "</tr>";
    }

    echo "</table>";
    ?>

Thanks

Upvotes: 0

Views: 601

Answers (2)

Sougata Bose
Sougata Bose

Reputation: 31749

$rows = 10;
$cols = 50;
$x=1 ;
echo "<table border='1'>"; 
for($tr=1;$tr<=$rows;$tr++){

  $style = "green";
  if ($tr % 2 == 0) {
    $style = "#ccc";
  }
  echo "<tr style='background-color:".$style."'>";

  for($td=1;$td<=$cols;$td++)
  {

       echo "<td>$x</td>";
       $x++;

  }
  echo "</tr>";
}

echo "</table>";

Upvotes: 1

Allmighty
Allmighty

Reputation: 1519

You are outputting $td which resets at every new tablerow. Instead, you would like to output an incrementing $x, if I'm not mistaken.

 <?php
 $rows = 10;
 $cols = 50;
 $x=1 ;
 echo "<table border='1'>"; 

 for($tr=1;$tr<=$rows;$tr++){  
   echo "<tr>";

     for($td=1;$td<=$cols;$td++){
         echo "<td>" . $x . "</td>";
         $x++;
      }

   echo "</tr>";
 }

 echo "</table>";
 ?>

In response to your comment on another answer: if you would want alternating row colors, you could use $tr and check wether it is even or uneven:

if($tr % 2 == 0)
{
 // use color1
}
else
{
 // use color2
}

Upvotes: 0

Related Questions