0

Attempting to generate table columns and rows based on input. With smaller numbers it appears to work appropriately, for example inputting 2 rows and 3 cols. But when inputting slightly larger numbers like 5 for rows will output an incorrect amount of rows sometimes looping indefinitely.

if(isset($_POST['submit'])) {

    $rows = (int)$_POST['row_num'];
    $cols = (int)$_POST['col_num'];
    $n = 1;
    $e = 0;

    echo '<table id="">';

    while(($e < $rows) && ($e < $cols)) {

        for($i = 0; $i < $rows; $i++) {
            echo '<tr>';

            for($i = 0; $i < $cols; $i++) {
                echo '<td><input type="text" name="field_' . $n . '"></td>';
                $n++;
            }

            echo '</tr>';
        }

        $e++;
    }

    echo '</table>';
}
1
  • 4
    Why do you have the while loop? What is its purpose? The two foreach loops are all you need. Commented May 5, 2015 at 16:35

2 Answers 2

2

Firstly, you don't need the While loop, it's pointless and probably causing issues.

Secondly, you're using $i for both your rows and your columns, you can't use the same variable for both. Use $i for one and $j for the other. This should work:

if(isset($_POST['submit'])) {

    $rows = (int)$_POST['row_num'];
    $cols = (int)$_POST['col_num'];
    $n = 1;

    echo '<table id="">';

    for($i = 0; $i < $rows; $i++) {
        echo '<tr>';

        for($j = 0; $j < $cols; $j++) {
            echo '<td><input type="text" name="field_' . $n++ . '"></td>';
        }

        echo '</tr>';
    }

    echo '</table>';
}
Sign up to request clarification or add additional context in comments.

1 Comment

The while loop was left over from a previous version of this and i forgot to take out. Thanks for pointing that out. This works great now thank you for the help!
1

scope variable $i problem here :

for($i = 0; $i < $rows; $i++) {
    echo '<tr>';

    for($i = 0; $i < $cols; $i++) {
        echo '<td><input type="text" name="field_' . $n . '"></td>';
        $n++;
    } 
}

i guess 2nd for condition change $i to $j :

for($i = 0; $i < $rows; $i++) {
    echo '<tr>';

    for($j = 0; $j < $cols; $j++) {
        echo '<td><input type="text" name="field_' . $n . '"></td>';
        $n++;
    } 
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.