2010-04-05 151 views
10

如果沒有發現什麼,array_search()會返回什麼?[PHP]:如果找不到任何東西,array_search()會返回什麼?

我有以下邏輯的需要:引用的array_search()手冊頁

$found = array_search($needle, $haystack); 

if($found){ 
    //do stuff 
} else { 
    //do different stuff 
} 
+1

這是更快地嘗試一下,看看結果不是要求它。 – 2010-04-05 23:05:45

+0

檢查結果is_int()看到它,因爲它返回一個鍵.. – PolarTheDog 2016-12-09 23:06:04

回答

33

返回針的關鍵,如果它在數組中 ,FALSE否則爲


這意味着你必須使用類似:

$found = array_search($needle, $haystack); 

if ($found !== false) { 
    // do stuff 
    // when found 
} else { 
    // do different stuff 
    // when not found 
} 

注意我用了!==運營商,這確實一種敏感的比較;看到Comparison OperatorsType Juggling,並Converting to boolean有關;-)

+5

'注意我使用了!==運算符,它做了一個類型敏感的比較' - 這正是問題所在。 0評價爲false ...謝謝 – 2010-04-05 22:45:59

+0

不客氣:-) ;;我編輯了我的答案,以添加鏈接到手冊的其他相關頁面,順便提一下:-) – 2010-04-05 22:49:09

+0

謝謝,你搖滾! – 2010-04-05 22:52:37

1

從文檔的詳細信息:

搜索草垛的針,如果它在數組中,否則爲FALSE返回的關鍵。

0

據當時http://php.net/manual/en/function.array-search.php官方文檔:

警告這個函數可以返回布爾值FALSE,但也可能返回的結果爲FALSE一個 非布爾值。有關更多信息,請閱讀 布爾的部分。使用===運算符來測試此功能的 返回值。

見這個例子:

$foundKey = array_search(12345, $myArray); 
if(!isset($foundKey)){ 
    // If $myArray is null, then $foundKey will be null too. 
    // Do something when both $myArray and $foundKey are null. 
} elseif ($foundKey===false) { 
    // $myArray is not null, but 12345 was not found in the $myArray array. 
}else{ 
    // 12345 was found in the $myArray array. 
}