如果为false,则计数为1;如果为空,则计数为false.为什么? [英] 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');
我以为是...
- 如果有错误,那么我可以像if(!$ res)//echo错误一样检查它
- 如果它是空的,我可以像if(!count($ res))//没有行一样检查它
- 否则,我假设有一行并继续该过程...
但是
- 出现错误时,将返回false.在if(count($ ret))给出1.
- 如果我作为空数组返回,则if($ ret)条件失败(给出错误).
- when there is an error false is returned. In if(count($ret)) gives 1.
- 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.
此代码使用ajax调用.所以我返回了一个json响应.
this code is called using ajax. so i return a json response.
为什么count为1,如果空数组为false.
why count gives 1 and if empty array gives false.
我只是想用逻辑条件进行编码,而不是提供更多的关系条件.只是为了减少代码.
我在哪里可以得到所有这些php的烦人的东西,以便可以确保自己最终不会犯上述类似的逻辑错误.
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-在以上句子中 我指的不是错误,而是 事情困扰着我们.令我们着迷的东西 逻辑错误.
BUGGING - in the above sentence bugging i referred as not a bug but things bugs us. things which makes us logical errors.
我编辑了以下代码,包括以下内容,同时我得到了 https://stackoverflow的答复.com/users/451672/andrew-dunn
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');
推荐答案
为什么计数为1"-请参见 http://docs.php.net/count :
"why count gives 1" - see http://docs.php.net/count:
如果var不是数组,则将返回[...] 1.
If var is not an array [...] 1 will be returned.
并且如果空数组为false." -请参见 http://docs.php.net/language.types .boolean#language.types.boolean.casting :
"and if empty array gives false." - see http://docs.php.net/language.types.boolean#language.types.boolean.casting:
转换为布尔值时,以下值为FALSE:
[...]
- 具有零个元素的数组
When converting to boolean, the following values are considered FALSE:
[...]
- an array with zero elements
这篇关于如果为false,则计数为1;如果为空,则计数为false.为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!