Jump to content

[SOLVED] Creating php code to put odd numbers in a table.


talksr

Recommended Posts

This will display all odd numbers between 2 and 99

 

<?php

for ($i=3; $i<100; $i+=2){
   echo $i.'<br>';
}

?>

 

I'm not sure how you want the table, so if you need help with that, explain it a little.

Basically, I would like php to create the numbers and insert them into a table in a web page.

 

Well, I gave you the code to generate the numbers...now all you have to do is generate the HTML you want. If you don't know how to do that, then give a description of how you want the table to look.

<?php

echo '<table border=1>';

$cols = 1;
for ($i=3; $i<100; $i+=2){

   echo '<td>'.$i.'</td>';

   if ($cols == 5){
      echo '<tr>';
      $cols = 0;
   }
   
   $cols++;
}

echo '</table>';

?>

This line

for ($i=3; $i<100; $i+=2){

 

Is telling $i to start at 3, increase by 2 each time the loop runs, and to run the loop 99 times (since you want all odd numbers up to 99.

 

   if ($cols == 5){
      echo '<tr>';
      $cols = 0;
   }

 

I set up a counter named $cols, this counts how many times the loop has run...so if it has run 5 times, then $cols equals 5.  So that code checks if the loop has run 5 times, and if it has, to create a new row (since you want 5 numbers per line). Then it starts the counter over for the next row.

 

Hopefully those make sense :)

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.