5
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

PHPで配列内の同じキーの要素を足し算したい

Posted at

PHPの標準関数で、配列内の同一のキーの要素を足し算する方法って用意されていないですよね。
やり方はいろいろあるかなと思いますが、一つのやり方を忘備録として書き留めておこうかと思います。
こうやって書いた方がもっとスマートに計算できるよっていう方法がありましたら、コメント欄で教えてください!!

##foreachでまわして同じキーの要素を足し算する

$sample1 = array(4) {[0]=> 84, [1]=> 6, [2]=>3, [9]=>21}
$sample2 = array(4) {[0]=> 15, [1]=> 3, [2]=>0, [9]=>26}

$result = [];
foreach ($sample1 as $key => $val) {
    $result[] = $val + $sample2[$key];
}

$result = array(4) {[0]=> 99, [1]=> 9, [2]=>3, [9]=>47}

以上、ご参考までに!!!

5
2
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?