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.

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

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.

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>";
}
?>

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.