我不知道是什么导致了这个问题,但我会在下面发布代码,然后介绍一下我迄今为止所做过的和我得到的结果。
$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
。“第一个数组条目”不能为
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.";
}
isset
函数用于检查给定的变量是否存在且不为null
。 - decezeisset
和empty
权威指南。 - deceze