为什么count函数返回1表示false,0表示NULL表示

时间:2013-11-28 04:53:12

标签: php count

我正在浏览php中的count函数。在这里,http://docs.php.net/count我没有得到为什么count函数返回1表示false,0表示NULL

<?php

  $result = count(null);
  // $result == 0

  $result = count(false);
  // $result == 1
?>

这个答案(count of false gives 1 and if of an empty array gives false. why?)并不能说明我在寻找什么。

3 个答案:

答案 0 :(得分:3)

如果var不是数组或具有已实现Countable接口的对象,则将返回1。

参考:http://php.net/manual/en/function.count.php

答案 1 :(得分:1)

来自PHP doc

  

有一个例外,如果array_or_countable为NULL,则返回0。

答案 2 :(得分:0)

count()可能会为未设置的变量返回0,但对于已使用空数组初始化的变量,它也可能返回0。使用isset()来测试是否设置了变量。

    $b[0]  = 7;
    $b[5]  = 9;
    $b[10] = 11;
    $result = count($b);
    // $result == 3

    $result = count(null);
    // $result == 0

    $result = count(false);
    // $result == 1

参考:http://php.net/manual/en/function.count.php