0

hey there. I am new to php and just out of curiosity I am trying to build an html table using nested while loops. I expect the following code to produce a table, but it is not doing so.

<html>
<table border="1">
<?php
$r=1;
$rows = 5;

$c = 1;
$columns = 5;

while ($r <= $rows) {
	echo "<tr>";
		while ($c<=$columns) {
			echo "<td>d</td>";
			$c++;}
	echo "</tr>";
	$r++;
	}

?>
</table>
</html>

I wondered if anyone would know what's the problem with this code. Otherwise, when I substitute for loops in each case of while loops I get tables but with only reduced number of rows and columns. if I ask it to give out 5 rows, for example, it only returns 3.

Remember, I am only interested in using a while loop inside another while loop... just for exercising... any help is much appreciated.

3
Contributors
4
Replies
7
Views
7 Years
Discussion Span
Last Post by bibiki
0

Not sure if this is your problem, but I think you may need a <body> tag between your <html> and <table> tags.

0

thanks darkgan for your reply.
however, the code ought to work without the body tags. what the problem seems to be is that the while loop is a test on a boolean variable, which causes the inner (nested) while loop run only once... thank's for your reply, anyways.

1

Hey.

The problem is that the variable you use in the inner loop, $c , gets incremented correctly the first loop, giving you a single valid row, but when it comes to the second loop, it is already at 5, so the loop is never executed.

All you would have to do to fix this is to reset $c at the top of the outer loop, so the inner loop is counted correctly for ever row.

Like:

<?php
$r=1;
$rows = 5;

$c = 1;
$columns = 5;
while ($r <= $rows) {
    $c = 1; // <-- The only change.
    echo "<tr>";
    while ($c<=$columns) {
        echo "<td>d</td>";
        $c++;
    }
    echo "</tr>";
    $r++;
}
?>

Also, in situations like these you should consider using a for loop rather than a while loop.

<?php
$rows = 5;
$columns = 5;

for($x = 0; $x < $rows; ++$x)
{
    echo "<tr>";
    for($y = 0; $y < $columns; ++$y)
    {
        echo "<td>{$x}x{$y}</td>";
    }
    echo "</tr>";
}
?>
0

hey Atli,
thanks man. that was awsome. as I said in the first post, I am only exercising, and in an actual project I would take your advice and use the for loop. thank you very much.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.