count的次数给出1,如果是空的数组则给出false。为什么?

时间:2010-09-23 09:15:02

标签: php

我有一个只返回一行作为数组的函数。

我提供一个查询作为参数,它只会给出一行。

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');

我的想法是......

  1. 如果有错误,我可以检查它是否(!$ res)// echo error
  2. 如果它是空的,我可以检查它是否(!count($ res))// no rows
  3. 否则我认为有一行并继续进行...
  4. BUT

    1. 当出现错误时返回false。在if(count($ ret))中给出1。
    2. 如果($ ret)条件失败(假设),如果我返回空数组。
    3. //

      $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的回复。

      为什么count给出1,如果空数组给出错误。

      我只想用逻辑条件进行编码,而不是提供更多的关系条件。只是为了减少代码。

      我在哪里可以得到所有这些BUGGING的东西,以便我可以确保我不应该像上面那样做出逻辑错误。

        

      BUGGING - 在上面的句子中   我称之为不是一个bug而是   事情让我们烦恼。让我们成功的事情   逻辑错误。



      我编辑了以下代码以包含以下内容,同时我将此作为https://stackoverflow.com/users/451672/andrew-dunn的回复

      我可以这样做,但我仍然想知道为什么上面的解释

      if($fes===false)jerror();
      if(!$fes)jsuccess('status,4');      
      

3 个答案:

答案 0 :(得分:6)

“为什么算数为1” - 请参阅http://docs.php.net/count

如果var不是数组[...]将返回1。

“如果空数组给出错误。” - 请参阅http://docs.php.net/language.types.boolean#language.types.boolean.casting

转换为boolean时,以下值被视为FALSE:
[...]
  • 一个零元素的数组

答案 1 :(得分:2)

为什么不先检查$ret === false

答案 2 :(得分:2)

如果$myVariable不是数组,而是空,那么

$count = count($myVariable);

给出1

对于这种情况,我检查变量是“array”还是“bool(false)”。如果输出是数组,我使用count,如果它不是数组,我将数字设置为零。

if (is_array($myVariable)) {
    $count = count($myVariable);
} else {
    $count = 0;
}