Why?


#1


https://www.codecademy.com/en/courses/web-beginner-en-5YvPF/0/3?curriculum_id=5124ef4c78d510dd89003eb8#

$x++;  echo $x; //switching both statements will change output. Why?


$x = 0;
while ($x < 5) {
	$x++;     //Output: 1 to 5
	echo $x;
};

$x = 0;
while ($x < 5) {
	echo $x;   //Output: 0 to 4
	$x++;
};


#2

It should be...
lets go through it.........

$x = 0;
while ($x < 5) {
$x++;
echo $x;
};

> $x = 0;
> while (0 < 5) {             //    true
> 	$x++;                //     $x = 1;
> 	echo $x;            //      prints 1
> };
again
>  while (1< 5) {             //    true
> 	$x++;                //     $x = 2;
> 	echo $x;            //      prints 2
> };
>  while (2< 5) {             //    true
> 	$x++;                //     $x = 3;
> 	echo $x;            //      prints 3
> };
>  while (3< 5) {             //    true
> 	$x++;                //     $x =4;
> 	echo $x;            //      prints 4
> };
>  while (4< 5) {             //    true
> 	$x++;                //     $x = 5;
> 	echo $x;            //      prints 5
> };
>  while (5< 5) {             //    false
*************loop end******************

Now here

$x = 0;
while ($x < 5) {
echo $x;
$x++;
};

> $x = 0;
> while (0 < 5) {               //    true
> 	 echo $x;              //     prints 0
> 	   $x++;               //     $x = 1;
> };
again
> while (1 < 5) {               //    true
> 	 echo $x;              //     prints 1
> 	   $x++;               //     $x = 2
> };

> while (2 < 5) {               //    true
> 	 echo $x;              //     prints 2
> 	   $x++;               //     $x = 3;
> };

> while (3 < 5) {               //    true
> 	 echo $x;              //     prints 3
> 	   $x++;               //     $x = 4;
> };

> while (4 < 5) {               //    true
> 	 echo $x;              //     prints 4
> 	   $x++;               //     $x = 5;
> };

> while (5 < 5) {               //   false

**********loop end****************

I hope u'll understand now :slight_smile:


The arrangement of statements in while loop
#3

Thank You for the help!!! :slight_smile:


#4

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