![](/img/trans.png)
[英]in_array() doesn't work anymore as expected if the array is created with explode()
[英]in_array() doesn't work as expected with associative array
我不知道是什么導致了這個問題,但是我將在下面發布代碼,然后仔細檢查到目前為止我所做的事情以及獲得的結果。
$client_emails = array(
'email@ex-one.com' => null, // first array entry
'email@ex-two.com' => 'page_two',
'email@ex-three.com' => 'page_three',
'email@ex-four.com' => null,
);
$form_email = 'email@ex-two.com';
if (!empty($form_email)) {
if (isset($client_emails[$form_email])) {
$client_page = $client_emails[$form_email];
} else { $client_page = null; }
}
if (in_array($form_email, $client_emails)) {
if (!is_null($client_page)) {
echo 'All seems to be good! - ';
echo $client_page;
} else {
echo 'You can not be here.';
}
} else {
echo "For some reason this isn't working... 'in_array' should be finding the email in the array.";
}
上面的代碼是我一直在玩的代碼,它不起作用。 但是,如果我們將'first array entry' (comment)
從NULL
更改為TRUE
,它將起作用,如下所示:
$client_emails = array(
'email@ex-one.com' => true, // first array entry
'email@ex-two.com' => 'page_two',
'email@ex-three.com' => 'page_three',
'email@ex-four.com' => null,
);
從技術上講,整個過程現在都可以正常運行,但是TRUE
等於1
,現在腳本的其余部分無法正常工作,因為它將讀取該值為1
並回顯它。 我需要它為NULL
。
'first array entry'
不能為NULL
或FALSE
,唯一起作用的值為TRUE
。 如果$form_email
的值等於沒有值的鍵,則可以為空,如果鍵具有值並且第一個數組鍵的值不為TRUE
,則整個操作將以任何方式失敗。
我不明白發生了什么。 我有兩個問題:
編輯:
我也嘗試了以下方法:
$client_emails = array(
'email@ex-one.com' => 'null', // first array entry
'email@ex-two.com' => 'page_two',
'email@ex-three.com' => 'page_three',
'email@ex-four.com' => 'null',
);
$form_email = 'email@ex-two.com';
if (!empty($form_email)) {
if (isset($client_emails[$form_email])) {
$client_page = $client_emails[$form_email];
} else { $client_page = null; }
}
if (in_array($form_email, $client_emails)) {
if (!empty($client_page) && $client_page != 'null') {
echo 'All seems to be good! - ';
echo $client_page;
} else {
echo 'You can not be here.';
}
} else {
echo "For some reason this isn't working... 'in_array' should be finding the email in the array.";
}
您的問題是您的if語句:
if (in_array($form_email, $client_emails))
在這里,您以值( [NULL, "page_two", "page_three", NULL]
)搜索電子郵件,但是您需要查看鍵( ["email@ex-one.com", ..., "email@ex-four.com"]
)),因此只需使用array_keys()
,例如
if (in_array($form_email, array_keys($client_emails)))
//^^^^^^^^^^^ See here, so you serach the email in the keys
你為什么不使用array_key_exists
if(array_key_exists($form_email, $client_emails)){
}
您正在將$form_email
與$form_email
的值進行$client_emails
。
if (in_array($form_email, $client_emails)) {
應該將$form_email
與$client_emails
的鍵(而不是值)進行比較。 -嘗試-
if (in_array($form_email, array_keys($client_emails))) {
或檢查它們的存在-
if(array_key_exists($form_email, $client_emails)) {
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.