【发布时间】:2022-01-07 13:34:32
【问题描述】:
注意:我已经阅读了Function to set default value of associative array if the key is not present 和Default values for Associative array in PHP。
假设:
$a = array('foo' => '123');
$b = $a['bar']; // PHP Notice: Undefined index: bar
如果键不存在,我希望默认有一个空字符串 "",而不是 PHP 通知。
我知道解决办法是:
$b = isset($a['bar']) ? $a['bar'] : "";
// or, since PHP 5.3:
$b = $a['bar'] ?: ""; // but this still produces a "PHP Notice"!
有没有办法避免?: ""直接拥有:
$b = $a['bar'];
在没有通知的情况下获取""?
注意:这存在于 Python 中:
import collections
d = collections.defaultdict(str)
print(d['bar']) # empty string, no error
【问题讨论】:
-
如果你已经阅读了这些问题的答案,并且很清楚地表明不存在这样的功能,你为什么还要问同样的问题?
-
@miken32 因为我想通过删除 PHP 通知来进一步设置默认值(详细信息 here)。这个细节对我很重要。此链接问题未讨论此问题。
-
无法设置默认值。你的问题是“有没有办法......让
$b = $a['bar'];得到""而不通知?”这与另一个问题相同。答案仍然是否定的。您最接近的是$b = $a['bar'] ?? ""; -
@miken32 嗯,我还没想过这个。魔鬼在细节中,这和
?: ""有什么区别?编辑:我明白了,没有更多的通知,太好了!也许你可以用这个发布答案! -
我不想回答这个问题,我正在尝试确定为什么不应该将其作为重复项关闭。
标签: php arrays associative-array key-value defaultdict