need to create a multiplication table

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
puglover
Forum Newbie
Posts: 5
Joined: Tue Oct 06, 2009 3:09 pm

need to create a multiplication table

Post by puglover »

the code looks right but it wont work. i know the problem has to be in the table somewhere...any suggestions will be GREATLY apperciated!!

Code: Select all

<?php
$rowcolors = array ("purple", "red", "yellow", "orange", "blue", "pink");
 
?>
<html>
<head>
<title>
</title>
</head>
<body>
Create a multiplication table<p>
<form method="get" action="<?php $_SERVER['php_self'];?> ">
Enter number of rows<br />
<input type="text" name="rownum" size="10" value="<?php echo $_GET['rownum'];?>"><p>
Enter number of columns<br />
<input type="text" name="colnum" size="10" value="<?php echo $_GET['colnum'];?>"><p>
Select a color<br />
<select name="color">
<?php
for ( $i = 0; $i < count( $rowcolors ); $i++ )
{
    echo "<option value=\"" . $i . "\">" . $rowcolors[$i] . "</option>\n";
 
}
?>
<input type="hidden" name="do_php" value="true">
<p><input type="submit" value="Create Table">
</form>
<?php
 
if( isset( $_GET['do_php'] ) )
{
    echo "<table width=\"50%\" border=\"3\">\n";
    echo "<tr><td width='$cellwidth'>&nbsp</td>";
    for ( $j = 1; $j <= $_GET['colnum']; $j++ ) 
    { 
        echo "<th>" .$j . "</th>\n";
    }
    for ($i = 1; $i <= $_GET['rownum']; $i++ ) 
    {   
        echo "<tr>";
        echo "<td>".$i."</td>\n";
    }
    echo "</tr>";
    for ( $j = 1; $j <= $_GET['colnum']; $j++ ) 
    { 
        echo "<td>".$i * $j."</td>\n";
    }
 
   
}
 
echo "</table>";
?>
 
 
</body>
</html>
User avatar
Weiry
Forum Contributor
Posts: 323
Joined: Wed Sep 09, 2009 5:55 am
Location: Australia

Re: need to create a multiplication table

Post by Weiry »

im not sure why your using 3 for loops to create the table.
you should only require 2 loops, one to go across, one to go down.

Code: Select all

 
$times = array($_GET['rownum'],$_GET['colnum']);
print "<table>";
for($i=1;$i<=$times[0];$i++){
    print "<tr>";
    for($j=1;$j<=$times[1];$j++){
        print '<td>'.$i*$j.'</td>';
    }
    print "</tr>";
}
print "</table>";
 
storing the $_GET numbers in the array probably isnt the most efficient way, but thats how i had existing code setup, so i just copy/pasted it
Post Reply