PHP if(count($ array))和if($ array)是否意味着相同的东西?

ale*_*lex 5 php arrays

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

//example 1

$array = array();

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

}

// example 2

$array = array();

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

}
Run Code Online (Sandbox Code Playgroud)

谢谢!

gah*_*ooa 21

来自http://www.php.net/manual/en/language.types.boolean.php,它表示空数组被视为FALSE.


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

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

以来

  • count()> 0是不错的
  • 填充数组不是错误的

然后问题中说明的两个案例将始终按预期工作.


Bil*_*ard 5

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

$array = array();

if (empty($array)) {
   echo 'the array is empty';
}
Run Code Online (Sandbox Code Playgroud)

更具可读性。