PHP使用count()和数组

seb*_*seb 2 php

我试图使用count()函数获取数组中的元素数量,结果对我来说有点令人费解,考虑下面的例子.

假设提供的用户ID错误,因此没有匹配,那么计数函数的结果是否为0?但它是1.你能解释一下为什么吗?

谢谢

$q = mysql_query("select password from users where user_name = '" .  $userID   .   "'");
$check = mysql_fetch_array($q);

$result = count($check);

echo "RESULT:" . $result;
Run Code Online (Sandbox Code Playgroud)

Pet*_*ley 7

这是计算结果集中行的错误方法.首先,来自mysql_fetch_array()的文档

返回与获取的行对应的字符串数组,如果没有更多行,则返回FALSE.

因此,如果我们这样做

echo count( false );
Run Code Online (Sandbox Code Playgroud)

我们可以看到输出是1.为什么?因为count()文档也告诉我们

如果var不是数组或具有已实现Countable接口的对象,则将返回1.

要做正确的计数,请使用mysql_num_rows()

$q = mysql_query("select password from users where user_name = '" .  $userID   .   "'");
$result = mysql_num_rows( $q );

if ( 0 == $result )
{
  // no rows in result
}
Run Code Online (Sandbox Code Playgroud)