php - in_array() 不能按预期使用关联数组

标签 php arrays

我不知道是什么导致了这个问题,但我会在下面发布代码,然后查看我到目前为止所做的事情以及我得到的结果。

$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

'第一个数组条目' 不能为 NULLFALSE,唯一有效的值是 TRUE .如果 $form_email 的值等于一个没有值的键,如果该键有一个值并且没有 TRUE 的值,则它可以为空第一个数组键然后整个事情以任何方式失败。

Code to reproduce the issue

我不明白发生了什么。我有两个问题:

  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

关于php - in_array() 不能按预期使用关联数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30434465/

相关文章:

php - 将数据从 C++ exe 返回到 web

arrays - 表中逐行循环数组数据

javascript - 按字母顺序对关联数组/javascript 对象进行排序

c++ - 尝试读取数组C++时For循环崩溃程序

php - 如何通过内连接表进行排序

php - PDO 插入查询失败

php - $_POST 未通过 AJAX 调用设置

Php foreach 循环仅在检查重复项时在 mysql 中添加第一行

javascript - 制作一个棋盘,上面有两个皇后

Python乘法范围