【问题标题】:PHP Does if (count($array)) and if ($array) mean the same thing?PHP if (count($array)) 和 if ($array) 意思一样吗?
【发布时间】:2009-02-16 05:20:25
【问题描述】:

在 PHP 中,这些总是返回相同的值吗?

//example 1

$array = array();

if ($array) {
   echo 'the array has items';

}

// example 2

$array = array();

if (count($array)) {
   echo 'the array has items';

}

谢谢!

【问题讨论】:

    标签: php arrays


    【解决方案1】:

    来自http://www.php.net/manual/en/language.types.boolean.php,它说空数组被认为是 FALSE。


    (引用): 转换为布尔值时,以下值被视为 FALSE:

    • 布尔值 FALSE 本身
    • 整数 0(零)
    • 浮点数 0.0(零)
    • 空字符串和字符串“0”
    • 零元素数组
    • 一个成员变量为零的对象(仅限 PHP 4)
    • 特殊类型 NULL(包括未设置的变量)
    • 从空标签创建的 SimpleXML 对象

    自从

    • > 0 的 count() 不为假
    • 填充的数组不为假

    那么问题中说明的两种情况将始终按预期工作。

    【讨论】:

      【解决方案2】:

      那些总是返回相同的值,但我发现

      $array = array();
      
      if (empty($array)) {
         echo 'the array is empty';
      }
      

      更具可读性。

      【讨论】:

        【解决方案3】:

        请注意,第二个示例(使用count())明显慢,在我的系统上至少慢了 50%(超过 10000 次迭代)。 count() 实际上计算数组的元素。我不是很肯定,但我想将数组转换为布尔值的工作方式很像empty(),一旦找到至少一个元素就会停止。

        【讨论】:

          【解决方案4】:

          他们确实会。如果数组非空,则将数组转换为布尔值将返回 true,并且数组的计数为 true,且元素不止一个。

          另请参阅:http://ca2.php.net/manual/en/language.types.boolean.php#language.types.boolean.casting

          【讨论】:

            猜你喜欢
            • 2016-02-09
            • 2011-04-01
            • 2012-05-04
            • 1970-01-01
            • 2022-12-19
            • 1970-01-01
            • 1970-01-01
            • 2010-11-19
            相关资源
            最近更新 更多