John Cargo
John Cargo

Reputation: 2121

nested for loop giving irrelevant output

I want to print value from 1 to user_input_limit. But after every 4 value. there should be 1 break line, and for that i am using below code, which is not working. It repeats value from +1 in 2nd interation.

My Code :-

if(is_numeric($_GET['num'])) {
    $num = ceil($_GET['num']/4);

    for($i=1;$i<=$num;$i++) {

       echo '<div class="hello">';

        for($j=$i;$j<=$i+3;$j++) {
            echo $j.", ";
        }

       echo '</div>';

        echo '<br />';
    }
}

This works good for first row, but in next row , j becomes 2 which is not what i need , i want it to be 5. Like below

What i need :- User_input = 11

<div class='hello'>1,  2,  3,  4, </div> 
<div class='hello'>5,  6,  7,  8, </div>
<div class='hello'>9, 10,  11, </div>

My inside for loop is wrong and i am getting output like :-

What i am getting :-

1,  2,  3,  4, 
2,  3,  4,  5, 
3,  4,  5,  6, 

Can any one fix my algorithm.

Thanks

Upvotes: 2

Views: 81

Answers (3)

Ronin
Ronin

Reputation: 1693

For div-ed strings is:

if(is_numeric($_GET['num'])) {
    echo '<div class="hello">';

    for($i=1;$i<=$_GET['num'];$i++) {
        echo $i . ($i < $_GET['num'] ? ', ' : '');

        if ($i % 4 == 0) {
            echo '</div>' . ($i < $_GET['num'] ? '<div class="hello">' : '');
        }
    }

    echo $_GET['num'] % 4 ? '</div>' : '';
}

Upvotes: 1

Maxime Ch&#233;ramy
Maxime Ch&#233;ramy

Reputation: 18841

Don't use an inner loop.

if(is_numeric($_GET['num'])) {
    for($i=1;$i<=$_GET['num'];$i++) {
        if ($i % 4 == 1) {
            echo '<div class="hello">';
        }
        echo $i.", ";
        if ($i % 4 == 0 || $i == $_GET['num']) {
            echo '</div>';
        }
    }
}

Edit:

If you are wondering if it would be possible to use a nested loop, here a possible solution:

if(is_numeric($_GET['num'])) {
    for($i=0;$i<ceil($_GET['num']/4);$i++) {
        echo '<div class="hello">';
        for($j=$i*4+1;$j<=$i*4+4 && $j <= $_GET['num'];$j++) {
            echo $j.", ";
        }
        echo '</div>';
    }
}

As you can notice, it's ugly :).

Upvotes: 4

geomagas
geomagas

Reputation: 3280

Why not just

if(is_numeric($_GET['num'])) {
    $num = intval($_GET['num']);
    for($i=1;$i<=$num;$i++) {
        echo "$i, ";
        if(!($i%4)) echo '<br />';
        }
    }

Upvotes: 0

Related Questions