Kevin Test
Kevin Test

Reputation: 133

how to make while loop start counting from 1

I have a while loop which looks like this:

$condition2 = true;
$page = 1;

while($condition2){

    $page++;
    echo $page;



    if($page == 3){
        $condition2 = false;
    }
}

As you see i echo the page here. But it starts counting from 2 then goes to 3 etc. I want it to start counting from 1. so the output would be 1 -2 -3.

i tried making the default value outside the loop 0. This results in an endless loop.

Upvotes: 0

Views: 255

Answers (5)

Chris Strickland
Chris Strickland

Reputation: 3490

Combine the echo and increment together:

echo $page++;

You'll also have to change the exit condition:

$page > 3

So the entire code would be

$condition2 = true;
$page = 1;

while($condition2){

    echo $page++;

    if($page > 3){
        $condition2 = false;
    }

}

You can get rid of the if by assigning straight to $condition2:

$condition2 = true;
$page = 1;

while($condition2){

    echo $page++;
    $condition2 = ($page > 3);

}

And you could further shorten it up by making the loop dependent on $page, like this:

$page = 1;

while($page <= 3){

    echo $page++;

}

But if you want to use $page for something besides just echoing it in the loop, you'd have to modify this a little, so you're not modifying it while you're trying to use it:

$page = 0;

while($page++ < 3) { 

    echo $page; 
    //use $page for something

};

Upvotes: 4

Sonveer Singh
Sonveer Singh

Reputation: 21

You can also do like this

$condition2 = true;
$page = 1;
while($condition2){
    if($page == 3){
        $condition2 = false;
    }
    echo $page;
    $page++;
}

Upvotes: 1

Lucian Coanda
Lucian Coanda

Reputation: 57

What if you increment the counter at the end instead ?

$condition2 = true;
$page = 1;

while($condition2){

    echo $page;

    if($page == 3){
        $condition2 = false;
    }
    $page++;
}

Upvotes: 1

rpm192
rpm192

Reputation: 2454

Either set $page to zero by changing:

$page = 1;

to:

$page = 0;

Or echo the variable before adding 1 to it:

$condition2 = true;
$page = 1;

while($condition2){

    echo $page;
    $page++



    if($page == 3){
        $condition2 = false;
    }
}

Upvotes: 1

teh_raab
teh_raab

Reputation: 394

You're incrementing the page variable too soon. Add the page++ right at the end of the loop

Upvotes: 1

Related Questions