Posted at

[PHP] 配列で同じキーのものは数値を足し算したい


コード

$arr = ["hoge" => 1, "piyo" => 2, "fuga" => 1];

$arr2 = ["hoge" => 1, "fuga" => 3, "hogehoge" => 0];

foreach ($arr2 as $key => $val) {
if (array_key_exists($key, $arr)) {
$arr[$key] = $arr[$key] + $val;
} else {
$arr[$key] = $val;
}
}

print_r($arr)


返り値

Array

(
[hoge] => 2
[piyo] => 2
[fuga] => 4
[hogehoge] => 0
)