为什么这段代码是无限循环的? [英] Why is this code an infinite loop?
本文介绍了为什么这段代码是无限循环的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在完成此代码之前,我只是错误地对其进行了测试,并意识到它不会停止:
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";
}
为什么会产生无限循环?为什么PHP不会产生错误?
Why does this produce an infinite loop? And why doesn't PHP produce an error?
推荐答案
我做了一个简单的测试:
I did a simple test :
echo $i;
$var.$i = "any";
var_dump($var);
结果:
1string(3) "any"
anzstring(3) "any"
因此$ i被转换为"anz",并且没有通过验证就退出了循环.
So $i get transformed to "anz" and doesn't pass the validation to get out of the loop.
$ var.$ i =任何";是不是真的不对,我不知道您要做什么,但是如果您想填充和排列数组,则应该做更多类似的事情:
$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
}
这篇关于为什么这段代码是无限循环的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文