when you try this code the result is ... The number is 1
<?php
$i=1;
do
{
echo "The number is " . $i . "<br />";
$i++;
}
while ($i==10);
?>
but when you change this code to be like this the result is 2
<?php
$i=1;
do
{
$i++;
echo "The number is " . $i . "<br />";
}
while ($i==10);
?>
so why the result changed ..?
$i++; is post increment operator so it will increment value by 1 on next line
and it use same value on current line
First Case: you are doing echo $i and then doing increment
Second Case: you are incrementing $i++ before echo statement so by nature it will increase value by 1 on echo line
You get a different result because you are doing two different things. In the first code snippet, you set $i
to the value of 1
, echo it out, then increment $i
.
In the second code snippet, you set $i
to 1
, increment it (ie, give it the value of 2
) then echo $i
, which now has the value of 2
.
yes, the results will differ. In 1st case you are incrementing after printing. While In second case you are incrementing before printing.
in both cases the first iteration of a do-while loop is guaranteed to run. The condition is only checked at the end of the iteration.
and, in the case1 you have print the variable before incremented. so it shows 1. In case2 you have print the variable after increment it. so it shows 2.