2011-11-28 37 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 
.... 
相關問題