在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:
創建自
那麼問題中說明的兩種情況將始終按預期工作。
確實會的。將一個數組轉換爲一個布爾值,如果它是非空的,將會給出true,並且一個數組的計數對於多個元素是真實的。
參見:http://ca2.php.net/manual/en/language.types.boolean.php#language.types.boolean.casting
注意,第二實施例(使用count()
)是顯著慢,由至少50%的我的系統(超過10000次迭代)上。 count()
實際上計數數組的元素。我不積極,但我想像將一個數組轉換爲一個布爾類型非常類似於empty()
,並且一找到至少一個元素就會停下來。
那些總是返回相同的值,但我覺得
$array = array();
if (empty($array)) {
echo 'the array is empty';
}
是一個很大的可讀性。