php, infinite loop in while() loop

拈花ヽ惹草 提交于 2019-12-30 11:15:34

问题


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


回答1:


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




回答2:


You mean

$x == 9

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

while($x < 9)



回答3:


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



来源:https://stackoverflow.com/questions/7464430/php-infinite-loop-in-while-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!