簡體   English   中英

in_array()無法與關聯數組一起使用

[英]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'不能為NULLFALSE ,唯一起作用的值為TRUE 如果$form_email的值等於沒有值的鍵,則可以為空,如果鍵具有值並且第一個數組鍵的值不為TRUE ,則整個操作將以任何方式失敗。

重現問題的代碼

我不明白發生了什么。 我有兩個問題:

  1. 關於如何解決這個問題的任何建議?
  2. 如果您可以幫助我了解發生這種情況的原因-也許我做錯了什么?

編輯:

我也嘗試了以下方法:

$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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM