【发布时间】: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 中,这些总是返回相同的值吗?
//example 1
$array = array();
if ($array) {
echo 'the array has items';
}
// example 2
$array = array();
if (count($array)) {
echo 'the array has items';
}
谢谢!
【问题讨论】:
来自http://www.php.net/manual/en/language.types.boolean.php,它说空数组被认为是 FALSE。
(引用): 转换为布尔值时,以下值被视为 FALSE:
自从
那么问题中说明的两种情况将始终按预期工作。
【讨论】:
那些总是返回相同的值,但我发现
$array = array();
if (empty($array)) {
echo 'the array is empty';
}
更具可读性。
【讨论】:
请注意,第二个示例(使用count())明显慢,在我的系统上至少慢了 50%(超过 10000 次迭代)。 count() 实际上计算数组的元素。我不是很肯定,但我想将数组转换为布尔值的工作方式很像empty(),一旦找到至少一个元素就会停止。
【讨论】:
他们确实会。如果数组非空,则将数组转换为布尔值将返回 true,并且数组的计数为 true,且元素不止一个。
另请参阅:http://ca2.php.net/manual/en/language.types.boolean.php#language.types.boolean.casting
【讨论】: