Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

Im trying to get the amount of elements in an array using the count() function, 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;
share|improve this question
    
Debugging the code would give you some insight into what $result actually is. Also, don't forget your friend is_array(). –  allnightgrocery May 26 '10 at 18:16

4 Answers 4

up vote 7 down vote accepted

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
}
share|improve this answer

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

share|improve this answer
    
$numrows = mysql_num_rows($q); –  Owen Allen May 26 '10 at 18:18

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

share|improve this answer

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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.