3

我有下面的一段代码,它检查给定的键是否存在于数组中。但是在执行此代码时,我收到此错误:

“警告:array_key_exists() 期望参数 2 是数组,给定的布尔值”。我是 PHP 新手,不知道是什么导致了这个错误。

代码

$structure = imap_fetchstructure($connection, $id, FT_UID);

if (array_key_exists('parts', $structure))
{

};
4

3 回答 3

24

为了防止有人将布尔值或空值传递给函数,您可以$structure在使用它之前添加一个简单的检查以查看它是否是一个数组:

    if (is_array($structure) && array_key_exists('parts', $structure))
    {
       //...magic stuff here 
    }

'为什么'您的原始代码被破坏的简单答案是 imap_fetchstructure() 没有找到请求的消息并返回 a falsenull0。文档http://php.net/manual/en/function.imap-fetchstructure.php没有说明失败时返回的内容,但很容易猜到。大多数返回对象但无法完成的 php 函数在失败时返回 null 或 false(当我说失败时,我并不是指错误或异常,只是无法执行或找到您要求的任何内容)。

于 2012-10-05T13:21:35.597 回答
2

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.

于 2012-10-05T13:17:57.793 回答
1

PHP 文档说它将返回一个对象,但是如果您查看 PHP 源代码,您会看到它实际上在失败时返回 FALSE,并且只有在一切成功时才返回一个对象。

https://github.com/php/php-src/blob/master/ext/imap/php_imap.c#L2280

于 2012-10-05T13:26:23.723 回答