假设我们有以下数组:
$ourArray = [
'a' => 'a',
'b' => 'b',
];
我们尝试获取密钥'c'
(不存在)的值:
$someValue = $ourArray['c'] ?? null;
所以,之前的陈述不会引起任何注意,因为它只是isset
的语法糖。有关详细信息,请访问PHP site。
在PHP7.1中引入了symmetric array destructuring,因此我们的想法是对数组进行解构,避免通知,例如:
[
'c' => $someValue
] = $ourArray;
所以这会抛出Undefined index: c in $ourArray ...
。
那么,有没有办法避免PHP使用对称数组解构引发通知?并且不使用error_reporting
或ini_set
等功能。
答案 0 :(得分:5)
您可以使用@
运算符
https://secure.php.net/manual/en/language.operators.errorcontrol.php
@[
'c' => $someValue
] = $ourArray;
<强>声明强>
这个运营商是有争议的。它可能会隐藏函数调用中的有用错误消息。许多程序员即使花费很高也会避免使用它。对于作业,它是安全的。
根据h2ooooooo的评论。
如果您可以并且想要定义所有默认值,则可以使用以下代码。
[
'c' => $someValue
] = $ourArray + $defaults;
运营商+
很重要。函数array_merge
不会保留数字键。
$defaults
的定义可能如下所示。您必须为每个可能的键定义值。
$defaults = [
'a' => null,
'b' => null,
'c' => null,
'd' => null,
'e' => null,
'f' => null,
];
# or
$defaults = array_fill_keys(
['a', 'b', 'c', 'd', 'e', 'f'],
null
);
答案 1 :(得分:0)
据我所知,你的问题也许这会有所帮助。
$ourArray = [
'a' => 'a',
'b' => 'b',
];
foreach($ourArray as $key => $value){
if($key == "c"){
echo "Value Exist <br>";
}
}
答案 2 :(得分:0)
你可以尝试:
[
'c' => $someValue
] = $ourArray + ['c' => null];