未找到PHP哈希键:预期的行为是什么?
我听说,如果您试图访问不存在的散列中的密钥,则会出现错误 然而,我似乎只得到一个空字符串,或者一个空值 例如:未找到PHP哈希键:预期的行为是什么?,php,hashtable,lookup,Php,Hashtable,Lookup,我听说,如果您试图访问不存在的散列中的密钥,则会出现错误 然而,我似乎只得到一个空字符串,或者一个空值 例如: <?php $hash = array("abc" => 123, "def" => 456 ); echo "a key that's in the hash: <" . $hash["abc"] . "><br />"; echo "a key that's not in the hash: <" .
<?php
$hash = array("abc" => 123,
"def" => 456
);
echo "a key that's in the hash: <" . $hash["abc"] . "><br />";
echo "a key that's not in the hash: <" . $hash["ghi"] . ">";
?>
您可能正在隐藏您的通知错误(更多信息)。
将以下内容放在脚本的顶部:
error_reporting(E_ALL);
ini_set('display_errors', true);
error_reporting(E_ALL);
ini_set('display_errors', true);
正如Wesley van Opdorp所说,您当前的错误报告设置可能会隐藏通知错误
可以使用此代码段(在脚本顶部)启用所有错误:
无论如何,我建议您通过isset()
检查某个密钥是否存在:
这取决于错误报告设置。
如果设置了error\u reporting=E\u ALL
>php -d error_reporting='E_ALL' -r '$a=array(); print $a["b"];'
PHP Notice: Use of undefined constant b - assumed 'b' in Command line code on line 1
PHP Stack trace:
PHP 1. {main}() Command line code:0
....
这是什么意思--隐藏您的通知
?我认为我无法控制配置文件。@MattFenwick-通知是较低级别的警告,在不中断执行的情况下被忽略。实际上,您不需要更改conf文件,您可以在执行过程中以编程方式使用ini\u set
,正如韦斯利所描述的那样,以查看消息。@deacondespreado--谢谢各位,我现在收到一个警告。我想可能还有一种方法可以覆盖默认配置,使其抛出不可忽略的错误?@MattFenwick Yep,您只需在PHP.ini中设置error\u reporting=E\u ALL
和display\u errors=on
。。。但这就是(有效地)使用上述解决方案所做的。如果您使用的是具有任何生产用途的机器,那么最好在运行时执行此操作,但如果它是纯dev服务器,则可以在PHP.ini中启用它。
if ( isset($array['key']) )
{
/* exists */
}
else
{
/* doesn't exist */
}
>php -d error_reporting='E_ALL' -r '$a=array(); print $a["b"];'
PHP Notice: Use of undefined constant b - assumed 'b' in Command line code on line 1
PHP Stack trace:
PHP 1. {main}() Command line code:0
....