PHP Control Structures Ex. #4: Nested For Loops
HTML tables involve a lot of repetitive coding - a perfect place to use for loops. You can do even more if you nest the for loops.
In this PHP exercise, use two for loops, one nested inside another. Create the following multiplication table:
1 | 2 | 3 | 4 | 5 | 6 | 7 |
2 | 4 | 6 | 8 | 10 | 12 | 14 |
3 | 6 | 9 | 12 | 15 | 18 | 21 |
4 | 8 | 12 | 16 | 20 | 24 | 28 |
5 | 10 | 15 | 20 | 25 | 30 | 35 |
6 | 12 | 18 | 24 | 30 | 36 | 42 |
7 | 14 | 21 | 28 | 35 | 42 | 49 |
Unless you want to try your hand at CSS styling, don't be concerned about the appearance of the table, its borders and text alignment. The point of the exercise it to create the data and the table tags using the for loops.
 
 
Here's the script:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="content-type" content="text/html;charset=iso-8859-1" />
<title>Nested Loop Multiplication Table</title>
</head>
<body>
<h2>Nested Loop Multiplication Table</h2>
<?php
//Generate an HTML table
echo "<table border=\"1\">";
//Generate table data showing the numbers 1-7 multiplied by each other,
//starting with the rows.
for ($row=1; $row<=7; $row++){
echo "<tr>\n";
//Generate each entry in the row to create the columns.
for ($col=1; $col<=7; $col++){
//First, do the math.
$x=$col * $row;
//Then send the value to the table with the table data tags.
echo "<td>$x</td>\n";
}
echo "</tr>";
}
echo "</table>";
?>
</body>
</html>
See the output of the script in a separate window here. You can also view the output's HTML source from the new window, if you need to check that.
To open a PHP code editor in a new tab, click here.
Comments
I suggest a slightly modified
I suggest a slightly modified solution, I entered the data directly as the product of the row and column number:
PS: I also styled the table to make it like in the example.
is this right?
hi.
I used your line:
echo "";
but dont know why it didnt work for me so i thought to exempt the table from the script & it worked (sorry, i am just about a wk old in programming as a whole- working against a deadline)..
So, is this acceptable? Thx!
<?php
}
}
?>
alternate script
}
}
check this
{
{
}
}
Simple table with a pinch of CSS styling. Cute..
the simple code i came up with:
}
then i place this code within the "head" section of html doc to style it a bit:
add additional styling to spice it up.