Ali
Ali

Reputation: 267049

Strange issue in PHP for loop

I have this simple loop:

for ($user = 1; $user <= 219; $user++)
{    
    echo "Yo <br />";
    $pos = 1;
    echo "Set pos to $pos <br />";
    do
    {
        echo "Doing user $user , $pos <br />";
        $pos++;
    }
    while ($pos <= 8);

    echo "Done user $user ,  $pos <br /><br ";
}

When I run this, only for the first iteration does it echo the first 'yo'. For every iteration from 2 to 219, the output starts from Set pos to $pos. Sample:

Yo 
Set pos to 1 
Done user 1 , 9 

Set pos to 1 
Done user 2 , 9 

Set pos to 1 
Done user 3 , 9 

Set pos to 1 
Done user 4 , 9 

Set pos to 1 
Done user 5 , 9 

What happened to this statement:

    echo "Yo <br />";

Why is it executed only for the first iteration and not for any others?

Upvotes: 1

Views: 95

Answers (2)

Francisco Presencia
Francisco Presencia

Reputation: 8841

It is executed in every iteration, you forgot to close <br /> at the end.

echo "Done user $user ,  $pos <br /><br />";

So, if you check the source of the page, it should say:

<br Yo <br />

Upvotes: 6

theftprevention
theftprevention

Reputation: 5213

If your echo "Yo <br />" was inside the do{} loop, then it would execute with every iteration, just before "Doing user [etc.]". Right now it's not inside the do{} loop, it's just inside the for() loop.

So, you'll only see the "Yo" after $pos exceeds 8 and the for loop begins another iteration.

Upvotes: 0

Related Questions