Skip to content

Instantly share code, notes, and snippets.

@gh640
Created February 6, 2016 12:47
Show Gist options
  • Select an option

  • Save gh640/d429e3b77dbf4ccdb1e5 to your computer and use it in GitHub Desktop.

Select an option

Save gh640/d429e3b77dbf4ccdb1e5 to your computer and use it in GitHub Desktop.
PHP: 配列の要素同士を足し合わせた配列を生成する関数
<?php
/**
* ふたつの数値からなる配列の各要素を足しあわせた配列を返す
*
* array_map() を使いたいが長さが違う場合の挙動などが不明なので for ループで計算しています。
*
* @param float[] $a1
* 数値の配列。長さは $a2 と共通。
* @param float[] $a2
* 数値の配列。長さは $a2 と共通。
*
* @return float[]
* ふたつの配列の同じインデックスの値を足し合わせた配列。
*/
function sum_arrays($a1, $a2) {
$sum_array = array();
$total_index = max(count($a1), count($a2));
for ($i = 0; $i < $total_index; $i++) {
$v1 = isset($a1[$i]) ? $a1[$i] : 0;
$v2 = isset($a2[$i]) ? $a2[$i] : 0;
$sum_array[$i] = $v1 + $v2;
}
return $sum_array;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment