php 警告:array_key_exists() 期望参数 2 是数组,给定布尔值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12747066/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Warning: array_key_exists() expects parameter 2 to be array, boolean given
提问by ashajf
I have the below piece of code which checks the given key exists in the array. But when executing this code I get this error:
我有下面的一段代码,用于检查数组中是否存在给定的键。但是在执行此代码时,我收到此错误:
"Warning: array_key_exists() expects parameter 2 to be array, boolean given". I am new to PHP and no idea what causes this error.
“警告:array_key_exists() 期望参数 2 是数组,给出布尔值”。我是 PHP 新手,不知道是什么导致了这个错误。
Code
代码
$structure = imap_fetchstructure($connection, $id, FT_UID);
if (array_key_exists('parts', $structure))
{
};
回答by Ray
To protect against someone passing a boolean or null into the function, you can add a simple check to see if $structureis an array before using it:
为了防止有人将布尔值或空值传递给函数,您可以$structure在使用它之前添加一个简单的检查以查看它是否为数组:
if (is_array($structure) && array_key_exists('parts', $structure))
{
//...magic stuff here
}
The simple answer to 'why' your original code is broken is that imap_fetchstructure() isn't finding the requested message and toand returning a false, null, or 0. The documentation http://php.net/manual/en/function.imap-fetchstructure.phpdoesn't indicate what's returned on failure, but it's easy to guess. Most php functions that return objects but are unable to complete return a null or false on failure (when I say failure I don't mean error or an exception, just couldn't do or find whatever you asked of it).
“为什么”您的原始代码被破坏的简单答案是 imap_fetchstructure() 没有找到请求的消息并返回一个false, null, 或0。文档http://php.net/manual/en/function.imap-fetchstructure.php没有指出失败时返回的内容,但很容易猜到。大多数返回对象但无法完成的 php 函数在失败时返回 null 或 false(当我说失败时,我不是指错误或异常,只是无法执行或找到您要求的任何内容)。
回答by Kareem
The PHP documentation says it will return an object, however if you view the PHP source code you'll see it actually returns FALSE on failure, and only returns an object if everything succeeds.
PHP 文档说它将返回一个对象,但是如果您查看 PHP 源代码,您会看到它实际上在失败时返回 FALSE,并且只有在一切成功时才返回一个对象。
https://github.com/php/php-src/blob/master/ext/imap/php_imap.c#L2280
https://github.com/php/php-src/blob/master/ext/imap/php_imap.c#L2280
回答by Ben Fransen
I'm guessing imap_fetchstructure()is returning false, meaning the function fails to complete your desired task. To debug, see what print_r($structure);outputs.
我猜imap_fetchstructure()是返回 false,这意味着该函数无法完成您想要的任务。要调试,请查看print_r($structure);输出。

