2014-03-27 83 views
1

我有一個數組,當我打印像這樣print_r($userExists);PHP如果數組爲空

輸出返回Array ()我寫了這個代碼告訴我,如果數組爲空或不:

if(isset($userExists)){ 
     echo 'exists'; 
    }else{ 
     echo 'does not exists'; 
    } 

但無論如果數組是空的或不是,它只返回exists什麼我做錯了,被填充數組的時候,它看起來像這樣Array ([0] => Array ([id] => 10))

+0

甚至設置了一個空數組。你可以檢查計數($ userExists) – ToBe

回答

7

使用

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_elementscount()稱爲(看看here

php manual



*(不工作,你想/需要)

+1

值得指出的是,如果沒有設置'$ userExists','count($ userExists)'會產生錯誤,而'empty($ userExists)'不會產生錯誤。 – Styphon

+0

@Styphon正如我一直告訴你的,已經確定變量* does *存在,否則'print_r'會拋出一個錯誤,而不是返回一個空數組。 –

+0

@Styphon:是的,你說得對。我正在更新我的答案:) – DonCallisto

1

使用如下

if(isset($userExists) && count($userExists) > 0){ 
     echo 'exists'; 
    }else{ 
     echo 'does not exists'; 
    } 

OR

可以檢查該變量是一個數組,並且具有一定的價值

if(is_array($userExists) && count($userExists) > 0){ 
    echo 'exists'; 
}else{ 
    echo 'does not exists'; 
} 
0
$userExists = array(); 

變量存在,並且已設置。這就是isset測試的結果。

你想要的是:

if($userExists) echo "exists"; 
+0

如果它不存在,會導致錯誤。 – Styphon

+0

@Styphon但是我確定它確實存在,OP也是這樣做的,在其上使用'print_r'。 –

+0

但是你忽略了其他的東西,當它不存在時。當它不存在時,代碼會拋出錯誤。這是給OP的不好建議。 – Styphon

0

你並不需要,如果額外的檢查!

if($array){ 
// Will execute only if there is any value inside of the array 
} 

通過使用,如果沒有必要檢查是否有任何值可用! 您正在使用的變量「isset」可能不存在像$ _GET值或$ _SESSION等等.... 「空」的PHP文件空只能在字符串檢查字符串值

,而不是陣列