Hello Everyone,

I know that , The do...while statement will always execute the block of code once, it will then check the condition, and repeat the loop while the condition is true.
but when i am running this code

<?php
$num = 1;
do 
    {
    $num++;
    echo $num;
    }
while ($num<=5)
?>

why the ouput is 23456 anhd not 2345 ?

Recommended Answers

All 8 Replies

Because you have $num<=5 . It will run the loop again when $num = 5 , so you get $num++, making $num = 6.

To cut off at 5, take the "=" out of the while condition.

why it will run the loop again when $num = 5 according to condition ?

Well, walk through it step-by-step:
When $num = 1:

  • $num++; is executed, making $num = 2
  • echo $num; will print out "2"
  • while condition is TRUE, since 2 is LESS THAN OR EQUAL to 5

When $num = 2:

  • $num++; is executed, making $num = 3
  • echo $num; will print out "3"
  • while condition is TRUE, since 3 is LESS THAN OR EQUAL to 5

Let's skip to 4:

  • $num++; is executed, making $num = 5
  • echo $num; will print out "5"
  • while condition is TRUE, since 5 is LESS THAN OR EQUAL to 5
    • 5 = 5, so TRUE

Therefore, since $num = 5 and the condition accepts all number up to and including 5, we will run the loop again:
When $num = 5:

  • $num++; is executed, making $num = 6
  • echo $num; will print out "6"
  • while condition is now FALSE, because 6 is GREATER THAN 5.

Does it make sense now?

Ok, thanks
Hey..! but when i'm incrementing after printing the first value why the output is 12345 ?

i.e

<?php
$num = 1;
do 
	{
	echo "The number is " . $num . "<br />";
	$num++;
	}
while ($num<=5);
?>

Because $num starts at 1. If you echo before incrementing then the number hasn't changed to 2 yet. it changes to 2 at $num++

Member Avatar for rajarajan2017

Why don't you take a notebook or slate and try it for every loop outputs?

I agree with rajarajan. When you first start programming it is very useful to grab a pen and a piece of paper and work through the changes in the variables' content step by step until you get the hang of it.

Member Avatar for diafol

I've always found 'do-while' more difficult than just a 'while'

$num = 1;
while($num <= 5){
   echo "The number is " . $num . "<br />";
   $num++;
}

Pre-process test (while) - check value before any code is run.
Post-process test (do-while) - check value after code is run.

I suppose it depends upon the implementation, but I've very rarely HAD to use do-while. Come to think of it, I can't remember the last time I used it.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.