[英]in_array doesn't make any sense
$arr = array(
'test' => array(
'soap' => true,
),
);
$input = 'hey';
if (in_array($input, $arr['test'])) {
echo $input . ' is apparently in the array?';
}
結果:嘿顯然在陣列中?
這對我沒有任何意義,請解釋原因。 我該如何解決這個問題?
這是因為true == 'hey'
由於類型雜耍 。 你在尋找的是:
if (in_array($input, $arr['test'], true)) {
它強制基於===
而不是==
進行相等性測試。
in_array('hey', array('soap' => true)); // true
in_array('hey', array('soap' => true), true); // false
為了更好地理解類型雜耍你可以玩這個:
var_dump(true == 'hey'); // true (because 'hey' evaluates to true)
var_dump(true === 'hey'); // false (because strings and booleans are different type)
更新
如果你想知道是否設置了數組鍵 (而不是存在一個值),你應該像這樣使用isset()
:
if (isset($arr['test'][$input])) {
// array key $input is present in $arr['test']
// i.e. $arr['test']['hey'] is present
}
更新2
還有array_key_exists()
可以測試數組密鑰的存在; 但是,只有在相應的數組值可能為null
情況下才應該使用它。
if (array_key_exists($input, $arr['test'])) {
}
您正在將數組用作字典,但是當您像數組一樣使用它時,將使用in_array
函數。 查看文檔 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.