如何在键不存在的情况下向数组添加值


How to add a value to an array it the key doesn't exist

我想这样做:

foreach($values as $key => $value){
    //modify the key here, so it could be the same as one before
    //group by key and accumulate values
    $data[$key]['total'] += $value - $someothervalue;
}

在php中是可能的吗?还是我总是要先检查这个?

isset($data[$key]['total'])

如果我理解正确的话,你可以不检查是否只在php7及以上版本中存在

foreach($values as $key => $value)
    $data[$key]['total'] = ($data[$key]['total'] ?? 0) + $value - $someothervalue;;

无论如何PHP允许你创建这样的新键,但不要忘记在你的服务器中禁用错误报告,以避免通知…

Php允许将NULL值添加到数字(当用于数字操作+,-,*时将其处理为0),因此如果您不介意覆盖它(并且从+=操作符我认为您不介意),则不需要检查isset($data[$key]['total'])

可以使用+=增加一个不存在的键。如果它不存在,PHP将自动创建它,初始值为null,当您尝试添加它时,它将被强制转换为零。这将在每次发生时生成两个通知:

注意:未定义offset: x

其中x$key

的值

注意:未定义索引:total

如果你不在乎这些通知,那就去吧。它会成功的。如果您确实关心这些通知,则必须在对其进行任何操作之前检查该键是否存在。正如您所说的isset($data[$key]['total'])将为此工作,但实际上您只需要检查isset($data[$key]),因为您只为每个$key写入'total'

foreach($values as $key => $value){
    //modify the key here, so it could be the same as one before
    //group by key and accumulate values
    $inc = $value - $someothervalue;
    if (isset($data[$key])) {
        $data[$key]['total'] += $inc;
    } else {
        $data[$key]['total'] = $inc;
    }
}

我建议这样做,因为我确实关心通知。还有很多其他的问题在讨论这个问题。

他们都比较老,按照现在的标准可能是基于意见的,但是其中的一些意见可能会提供一些洞察力来帮助你做出决定。

谢谢大家的回答。我选了:

foreach($values as $key => $value){
    //modify the key here, so it could be the same as one before
    //group by key and accumulate values
    $inc = $value - $someothervalue;
    if (!isset($data[$key]['total']){
        $data[$key]['total'] = 0;
    }
    $data[$key]['total'] = += $inc;
}