任何人都可以解釋爲什麼這是返回非空嗎?PHP空函數 - 關聯數組
<?php
$attributes=array("description"=>"","quantity"=>"","price"=>"","discount"=>"");
if(empty($attributes))
echo 'empty';
else
echo 'non empty';
exit;
?>
任何人都可以解釋爲什麼這是返回非空嗎?PHP空函數 - 關聯數組
<?php
$attributes=array("description"=>"","quantity"=>"","price"=>"","discount"=>"");
if(empty($attributes))
echo 'empty';
else
echo 'non empty';
exit;
?>
從manual documentation for empty()
:
檢查一個變量是否被認爲是空的。 如果變量不存在或者其值等於FALSE,則該變量被認爲是空的。如果變量不存在,則empty()不會生成警告。
在這種情況下,變量$attributes
存在並且它不等於FALSE。所以empty()
將返回布爾值FALSE
。
要檢查它們中的每一個是空的和回聲的消息:
foreach ($attributes as $key => $value) {
if (empty($value)) {
echo "'$key' is empty\n";
}
}
要檢查是否所有的數組的值是空的:
if(!array_filter($attributes)) {
echo 'All values are empty';
}
要檢查是否有任何的數組值爲空:
if (array_search('', $attributes) !== FALSE) {
echo 'One of the values in the array is empty';
}
使感覺..感謝清晰的代碼解釋.. :) –
這是因爲你有一個空字符串數組,它不是一個空數組。
好吧。謝謝。但有什麼更好的方法來檢查上述數組是否爲空? –
是的..展望..感謝您的更新.. –
這是因爲數組元素中有鍵,雖然它沒有值,所以它被認爲是非空的。 –