使用
if(!empty($userExists)) {
echo 'exists';
}
else {
echo 'does not exists';
}
或
if(count($userExists)) {
echo 'exists';
}
else {
echo 'does not exists';
}
Howev呃更安全地使用empty()
就好像這個變量不存在一樣,你的腳本不會因爲exception
而停止,而count()
會這樣做。
isset
由於此變量已設置(即存在),因此即使爲空也不「正在工作」。
所以,基本上,isset
將
確定是否一個變量被設定,並沒有NULL。
最後但並非最不重要的,如果你想知道這是代碼優化「更好」,我可以告訴你一個小「祕密」:
count()
並不需要每次都遍歷數組知道因爲內部會存儲元素編號(如您所見),因此每次調用
count()
函數都會導致
O(1)
的複雜性。
ZEND_API int zend_hash_num_elements(const HashTable *ht)
{
IS_CONSISTENT(ht);
return ht->nNumOfElements;
}
zend_hash_num_elements
從count()
稱爲(看看here)
從php manual
*(不工作,你想/需要)
甚至設置了一個空數組。你可以檢查計數($ userExists) – ToBe