count()在while循环

时间:2015-12-14 00:57:21

标签: php while-loop count

我从数据库中获取数据,count()在while循环中获取数据后输出错误。为什么呢?

输出是:

Line: 1 
Line: 2
Count after loop: 3

代码:

while($line[] = mysqli_fetch_array($result)){
    echo 'Line: '.count($line);
}
echo 'Count after loop: '.count($line);

1 个答案:

答案 0 :(得分:2)

这是因为在第3次迭代中mysqli_fetch_array()将返回NULL,因为没有剩下的行,然后您将其添加到数组中。

On NULL,其值为FALSE,while循环将停止,但它将被添加到数组中。所以你有3个元素,例如

If rnd = 1 And Button3.Enabled Then
    Button3.Text = "O"
    Button3.Enabled = False
End If
If rnd = 2 And Button6.Enabled Then
    Button6.Text = "O"
    Button6.Enabled = False
End If
If rnd = 3 And Button5.Enabled Then
    Button5.Text = "O"
    Button5.Enabled = False
End If

执行此操作时可以看到:if。现在要解决这个问题,您可以简单地将代码放在while循环中以添加元素,例如

while($row = mysqli_fetch_array($result)){
    $line[] = $row;
    echo 'Line: '.count($line);
}
echo 'Count after loop: '.count($line);

因此,如果Array ( [0] => something [1] => something [2] => NULL ) 保持为NULL,则不会将var_dump($line);添加到$row

相关问题