Reputation: 341
Last question wasn't received well so I've done more reading and came up with a simple php program that accepts user input for number of rows and columns. A table is generated using nested while loop and I do understand that a 'For' loop is more suited for this and got it working using one. Trying to learn and get better so I want to figure this one out too. I'm getting one row only and no columns. I also want the iteration to produce rows and columns that appear like the example. Kind of frustrated the for loop was much easier to finally figure out.
W,row1,col1; W,row1,col2; W,row1,col3
W,row2,col1; W,row2,col2; W,row2,col3 etc...
php code:
<?php
if(isset($_GET['rows'])) {
$r = 1;
$c = 1;
$rows = 5;
$cols = 6;
while ($r <= $rows) {
echo '<tr>';
while($c <= $cols) {
echo '<td>W, '.'row' .$r.',col'.$c.';</td>';
$c++;
}
echo '</tr>';
$r++;
}
?>
Upvotes: 0
Views: 47
Reputation: 780798
You're never changing the variables that you're testing in the while
conditions, so the loops are infinite. You need to decrement the variables each time.
And you need to re-initialize $cols
before each inner loop. Otherwise, the end condition will already be met after the first iteration of the outer loop.
$count = 1;
$rows = $_REQUEST['rows'];
//while loop to create table
while ($rows-- >= 1) {
echo '<tr>';
$cols = $_REQUEST['cols'];
while ($cols-- >= 1) {
echo '<td>W,row1,col1;</td>';
$count++
}
echo '</tr>';
}
Upvotes: 1
Reputation: 255
YOu can do it like this:
if(isset($_GET['rows'])) {
//Create counters
$count = 1;
$rows = $_REQUEST['rows'];
$cols = $_REQUEST['cols'];
//for loop to create table
for($i=1;$i<=$rows;$i++){
echo '<tr>';
for($j=1;$j<=$cols;$j++){
echo '<td>W,'.'row'.$i.',col'.$j.';</td>';
}
echo '</tr>';
}
}
Upvotes: 0