while 循环条件奇怪的行为 php
While loop condition strange behavior php
谁能解释一下第一个循环和第二个循环有什么区别,为什么第一个正常工作而第二个忽略条件?
我唯一改变的是,我不是直接在 $i 变量上增加值,而是通过 $q 变量增加值(注意第二个循环是无限的)
$i = 0;
while ($i < 10) {
$i++;
}
$i = 0;
$q = $i;
while ($q < 10) {
$i++;
}
$i = 0;
$q = $i;
// $q is now equals to $i, but it is not
// a reference, it only has the value of $i
// at this specific moment.
while ($q < 10) {
// $i == 0
// $q == 0
$i++;
// $i == 1
// $q == 0
}
$q
将永远为 0,因为您不递增它,所以 $q < 10
始终是 true
.
但是在你的第一个循环中:
$i = 0;
while ($i < 10) {
// $i == 0
$i++;
// $i == 1
}
在第十次迭代时,$i < 10
变为 false
并且循环停止。
谁能解释一下第一个循环和第二个循环有什么区别,为什么第一个正常工作而第二个忽略条件? 我唯一改变的是,我不是直接在 $i 变量上增加值,而是通过 $q 变量增加值(注意第二个循环是无限的)
$i = 0;
while ($i < 10) {
$i++;
}
$i = 0;
$q = $i;
while ($q < 10) {
$i++;
}
$i = 0;
$q = $i;
// $q is now equals to $i, but it is not
// a reference, it only has the value of $i
// at this specific moment.
while ($q < 10) {
// $i == 0
// $q == 0
$i++;
// $i == 1
// $q == 0
}
$q
将永远为 0,因为您不递增它,所以 $q < 10
始终是 true
.
但是在你的第一个循环中:
$i = 0;
while ($i < 10) {
// $i == 0
$i++;
// $i == 1
}
在第十次迭代时,$i < 10
变为 false
并且循环停止。