开发者

PHP using count() with array

开发者 https://www.devze.com 2023-01-01 17:22 出处:网络
Im trying to get the amount of elements in an array using the count() functio开发者_运维知识库n, the result is a bit puzzling to me, considere the following example.

Im trying to get the amount of elements in an array using the count() functio开发者_运维知识库n, the result is a bit puzzling to me, considere the following example.

Assume that the user ID provided is wrong, and therefore had no matches, wouldnt then the result of the count function be 0? yet it is 1. can you explain to me why?

thanks

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

$result = count($check);

echo "RESULT:" . $result;


That's the wrong way to count rows in a result set. First of all, from the documentation on mysql_fetch_array()

Returns an array of strings that corresponds to the fetched row, or FALSE if there are no more rows.

Ergo, if we do this

echo count( false );

We can see the output is 1. Why? Because the count() documentation tells us that as well

If var is not an array or an object with implemented Countable interface, 1 will be returned.

To do a proper count, use 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
}


use mysql_num_rows instead of count. count returns 1 for the value FALSE


count() returns 1 because in case of failure $check is not an array.

From the documentation:

If var is not an array or an object with implemented Countable interface, 1 will be returned

But you should anyway handle error cases directly (if the query fails your code shouldn't even get to the point where you analize its results). Also as other have correctly said, that's not how you count the number of results a query returns as that's what mysql_num_rows() is for


mysql_fetch_array returns false if there are no more rows. count(false) = 1.

Try using mysql_num_rows if you want to count the number of results.

0

精彩评论

暂无评论...
验证码 换一张
取 消