While循环在使用变量时未按预期工作


While loop not working as expected with variable

当我删除&& $f<4时,下面的代码运行良好,但有了它,它就不起作用了。

PHP:

$titles=array();
$f=0;
while ($row=mysql_fetch_assoc($query) && $f<4){  //this line doesn't work
        $titles[]=$row['questiontitle'];
            echo "<div class='questionPreview'>$titles[$f]</div>";
            $f++;
        }

如果我对你的解释正确,我认为你有优先级问题。试试这个:

while (($row=mysql_fetch_assoc($query)) && ($f<4)){

=has lower precedence than&amp;。这意味着首先评估&&运算符。

这意味着你的代码实际上是这样的:

while ($row = (mysql_fetch_assoc($query) && $f<4)){  //this line doesn't work

因此,换句话说,进行MySQL查询和比较,如果两者都为真,则将$row设置为true;否则设置为false

您需要使用括号来确保完成正确的操作:

while (($row=mysql_fetch_assoc($query)) && ($f<4)){

这可能是因为$rowtrue,而不是数组:

$ php -r 'var_dump($row = pow(2,2) && true,$row);'
bool(true)
bool(true)
$ php -r 'var_dump($row = pow(2,2) && false,$row);'
bool(false)
bool(false)

(这里pow是随机函数)

这是因为CCD_ 10具有比CCD_ 11更高的优先级。一如既往,使用():解决

while ( ($row = mysql_fetch_assoc($query) ) && $f<4){