0

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 ?

4
Contributors
8
Replies
9
Views
7 Years
Discussion Span
Last Post by diafol
1

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.

0

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

1

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?

0

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);
?>
0

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++

0

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.

0

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.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.