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

时间:2016-08-19 13:24:08

标签: php arrays

我想做这样的事情:

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'])

4 个答案:

答案 0 :(得分:0)

Php允许向数字添加NULL值(在数字操作+,-,*上使用时将其处理为0),因此如果您不介意,则无需检查isset($data[$key]['total'])覆盖它(以及我认为你不介意的+=运算符。)

答案 1 :(得分:0)

如果我理解正确,你可以不检查密钥是否仅存在于PHP 7及以上版本中吗?

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

无论如何,php允许你创建这样的新密钥,但不要忘记在服务器中禁用错误​​重新启动以避免通知...

答案 2 :(得分:0)

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

  

注意:未定义的偏移:x

其中x$key

的值
  

注意:未定义索引:总计

如果您不关心通知,请继续。它会工作。如果您确实关心通知,则必须先检查密钥是否存在,然后再对其执行任何操作。正如您所说isset($data[$key]['total'])将适用于此,但实际上您只需要检查isset($data[$key]),因为您只为每个'total'$key

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;
    }
}

我建议这样做,因为我关心通知。有various other questions可以讨论这个问题。他们年龄较大,可能会根据现行标准以意见为基础关闭,但有些意见可能会提供一些帮助您做出决定的见解。

答案 3 :(得分:0)

感谢所有答案。我跟着去了:

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;
}