Why is this code an infinite loop?

戏子无情 提交于 2020-01-23 23:59:58

问题


Before completing this code, I just tested it by mistake and realized that it will not stop:

$var = "any"; 
for ($i=1; $i < 2; $i++){ 
    $var.$i = "any"; 
}

Why does this produce an infinite loop? And why doesn't PHP produce an error?


回答1:


I did a simple test :

echo $i;
 $var.$i = "any";
var_dump($var);

Result :

1string(3) "any"
anzstring(3) "any"

So $i get transformed to "anz" and doesn't pass the validation to get out of the loop.

$var.$i = "any"; is not really correct, i don't know what you are trying to do, but if you want to fill and array you should do something more like :

$var = array();
for ($i=1; $i < 2; $i++){ 
 $var[] = "any";
}

If you want to change your string letter by letter :

$var = "any";
    for ($i=1; $i < 2; $i++){ 
     $var[$i] = "a"; // asign a new letter to the string at the $i position
    }



回答2:


When you do the following $var.$i = 'any' you set the $i variable and the $var variable. So the the loop never stop running because var_dump($i < 1) returns true.

$var = 'var';
$i = 1;
$var.$i = 'var';

var_dump($i); 

Returns string(3) "var".

This loop will never stop because $i is always reset to 'var', which is smaller than 1.




回答3:


This is incorrect $var.$i = "any"; because this expression is equivalent to:

 $var.($i = "any");

Which assigns $i to new value, therefore the condition of which the while loops checks will always be true.




回答4:


PHP5.4+.

You will get 'anz' result, after $i++, when $i == 'any'. $i == 'any', after assignment and that is, actually, what it should get. Trick is in "$i='any'" part of line. Even when "=" has lower precedence then ".", why do you think that it shouldn't put 'any' inside $i?

Try this instead:

$var = "any"; 
for ($i=1; $i < 2; $i++){ 
 $i.$var = "anything";
}

And your loop will work. And $var will get "anything" value. This doesn't look like a bug. Just unexpected behaviour for somebody.



来源:https://stackoverflow.com/questions/17856152/why-is-this-code-an-infinite-loop

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