Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
884 views
in Technique[技术] by (71.8m points)

php - count of false gives 1 and if of an empty array gives false. why?

I have a function which returns only one row as array.

I give a query as a parameter which will exactly gives only one row.

function getFields($query)
{
    $t =& get_instance(); 
    $ret = $t->db->query($query);
    if(!$ret)return false;
    else if(!$ret->num_rows()) return array();
    else return $ret->row_array();
}
$ret = getFields('query string');

What i thought was ...

  1. if there is an error then i can check it like if(!$res)//echo error
  2. if it is empty i can check it like if(!count($res))// no rows
  3. else i assume that there is a row and continue the process...

BUT

  1. when there is an error false is returned. In if(count($ret)) gives 1.
  2. If($ret) conditions fails (gives false) if i return as empty array.

//

$ret = getFields('query string');
if(!$fes)jerror('status,0,msg,dberror');        
if(!count($fes))jerror('status,1,msg,no rows');     
// continue execution when there atleast one row.

this code is called using ajax. so i return a json response.

why count gives 1 and if empty array gives false.

i just wanted to code with logical conditions instead of giving more relations conditions. just to reduce code.

Where can i get all these BUGGING stuff of php so that i can make sure i should not end up making logical errors like the above.

BUGGING - in the above sentence bugging i referred as not a bug but things bugs us. things which makes us logical errors.



I edited this following code to include the following meanwhile i got this as the reply by https://stackoverflow.com/users/451672/andrew-dunn

i can do it like this but still i want to know why for the above explanation

if($fes===false)jerror();
if(!$fes)jsuccess('status,4');      
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

"why count gives 1" - see http://docs.php.net/count:

If var is not an array [...] 1 will be returned.

"and if empty array gives false." - see http://docs.php.net/language.types.boolean#language.types.boolean.casting:

When converting to boolean, the following values are considered FALSE:
[...]
  • an array with zero elements

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...