The arrangement of statements in while loop


#1


<?php
         $i = 0;
         
         while( $i < 10) {
            echo $i . "<br/>";
            $i++;
         }
        echo $i;
?>
//The while loop will output 0 to 9.
//$i equals 10. Why not 9?
      
<?php
         $i = 0;
         
         while( $i < 10) {
            $i++;
            echo $i . "<br/>";
         }
        echo $i;
?>
//The while loop will output 1 to 10.
//$i equals still 10.


#2

In your first loop you are outputting the value of i before you have incremented it by 1, which means that on the last iteration it prints i when it is equal to 9 and then increments i by 1.

In your second loop i is incremented before the value is echoed so on the last iteration it is incremented to 10 and then outputted.


#3

@mkordik is right.
you can check it too
https://discuss.codecademy.com/t/why/52632/2?u=rcodeman


#4

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.