2
/// infinite loop??
$x=1; 
while($x=9){ 
echo $x;
$x++;
}

i dont understand the reason behind, why the above code causes infinite loop in my opinion above code should output "9" once. but it outputs endless 999999999......

at first (when x is equal to 1) while statement is false so nothing happens, then x becomes 2 but again while statement is false;

So when x becomes 9 while statement is true so it should echo 9 then we add 1 due to x++; and it becomes 10 so while statement becomes false but as i see it doesnt because

it continues to echo 9999999.......

pls enlighten me regarding the above code. best regards.

note:i have checked the similar questions but cant find the answer for my situation thx

2
  • 4
    For this reason, you will see it written if (9 == $x) in many cases, to avoid such errors. Commented Sep 18, 2011 at 21:02
  • I think you should have assumed something was wrong from the very first moment when your x=9 made it into the while loop. If the while condition is false then $x++ wouldn't even have ran all. Commented Jul 17, 2015 at 17:33

3 Answers 3

10

$x=9 is an assignment, and is always true. Perhaps you meant $x==9, or some other relational operator.

Sign up to request clarification or add additional context in comments.

Comments

3

You mean

$x == 9

But in your example it won't do anything, because $x != 9. You probably mean

while($x < 9)

1 Comment

Old thread, but in case someone reads it. The But in your example it won't do anything, because $x != 9. You probably mean while($x < 9) is untrue. If he DOES write $x == 9, then the loop while stop as soon as $x becomes 9. So it will output 123456789 and then stop.
1

You are assigning the value of 9 to the variable x instead of performing a relational comparison. A common mistake. = is the assignment operator whereas == is the equality comparison operator.

http://en.wikipedia.org/wiki/Assignment_(computer_science)#Assignment_versus_equality

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.