2011-11-28 35 views
2

我听说如果您尝试访问不存在的散列中的密钥,则会出现错误。未找到PHP哈希键:期望的行为是什么?

但是,我似乎只是得到一个空字符串或空值。

例子:

<?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"] . ">"; 

?> 

输出是:

a key that's in the hash: <123> 
a key that's not in the hash: <> 

这是怎么回事?

我正在使用PHP v5.3.8。

回答

4

您可能隐藏了您的通知错误(更多信息here)。在你的脚本的顶部 将这个:

error_reporting(E_ALL); 
ini_set('display_errors', true); 
+0

这是什么意思 - '隐藏你的notices'?我不认为我可以控制配置文件。 –

+1

@MattFenwick - 声明是在不中断执行的情况下被忽略的低级警告。您实际上并不需要更改conf文件,您可以像Wesley描述的那样通过编程方式使用'ini_set'来查看消息。 – DeaconDesperado

+0

@DeaconDesperado - 谢谢你,我现在得到一个警告。我想有可能也有一种方法来覆盖默认配置,使其抛出不可忽略的错误? –

1

至于韦斯利面包车Opdorp说,当前的错误报告设置可以隐藏通知错误。

你能使用此代码段的所有错误(在你的脚本的顶部):我建议你

error_reporting(E_ALL); 
ini_set('display_errors', true); 

反正来检查,如果某个键是否存在通过isset()

if (isset($array['key'])) 
{ 
    /* exists */ 
} 
else 
{ 
    /* doesn't exist */ 
} 
0

这取决于error_reporting设置。 你会得到未定义偏移通知,如果你设置error_reporting = E_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 
.... 
相关问题