PHP Snippet 1:
$array = array(); // hungarian notation
$array[] = array(5, 10, 15, 20, 25, 30);
$array[] = array(1, 2, 3, 4, 5, 6);
$array[] = array(2, 6, 8, 10, 12, 14);
PHP Snippet 2:
Array
(
[0] => Array
(
[0] => 5
[1] => 10
[2] => 15
[3] => 20
[4] => 25
[5] => 30
)
[1] => Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
[5] => 6
)
[2] => Array
(
[0] => 2
[1] => 6
[2] => 8
[3] => 10
[4] => 12
[5] => 14
)
)
PHP Snippet 3:
$sumArray = array();
$arrayCount = count($array);
$elementCount = 0;
foreach($array as $subarray)
{
$count = count($subarray);
$elementCount = $elementCount < $count ? $count : $elementCount;
}
for($i = 0; $i < $elementCount; $i++)
{
$sumArray[$i] = 0;
for($j = 0; $j < $arrayCount; $j++)
{
$sumArray[$i] += $array[$j][$i];
}
}
print_r($sumArray);
PHP Snippet 4:
Array
(
[0] => 8
[1] => 18
[2] => 26
[3] => 34
[4] => 42
[5] => 50
)
PHP Snippet 5:
$array = array(); // hungarian notation
$array[] = array(5, 10, 15, 20, 25);
$array[] = array(1, 2, 3, 4, 5, 6);
$array[] = array(2, 6, 8, 10);
PHP Snippet 6:
Array
(
[0] => 8
[1] => 18
[2] => 26
[3] => 34
[4] => 30
[5] => 6
)
PHP Snippet 7:
$loopThrice = 3;
$getSum = 0;
$total = array();
$array0 = array(5, 10, 15, 20, 25, 30);
$array1 = array(1, 2, 3, 4, 5, 6);
$array2 = array(2, 6, 8, 10, 12, 14);
// find which arrray has the most values
for($a=0; $a < $loopThrice; $a++){
$max_index = (count(${'array'.$a}) > $max_index ? count(${'array'.$a}) : $max_index);
}
for($i=0; $i < $max_index; $i++){
for($a=0; $a < $loopThrice; $a++){
$total[$i] += ${'array'.$a}[$i];
}
}
print_r($total);
// prints Array ( [0] => 8 [1] => 18 [2] => 26 [3] => 34 [4] => 42 [5] => 50 )
PHP Snippet 8:
$array0 = array(5, 10, 15, 20, 25, 30);
$array1 = array(1, 2, 3, 4, 5, 6);
$array2 = array(2, 6, 8, 10, 12, 14);
$var_prefix = 'array';
$arr_count = 0;
$max_fields = 0;
while(isset(${$var_prefix.$arr_count})) {
$data[] = ${$var_prefix.$arr_count};
if(count(${$var_prefix.$arr_count})>$max_fields) {
$max_fields = count(${$var_prefix.$arr_count});
};
$arr_count++;
}
for($i=0; $i<$max_fields; $i++) {
$result[$i] = array_sum(array_column($data, $i));
}
echo '<pre>';
print_r($result);
echo '</pre>';
die();
PHP Snippet 9:
var_export(
array_map(fn() => array_sum(func_get_args()), $array0, $array1, $array2)
);
PHP Snippet 10:
var_export(
array_map(fn(...$cols) => array_sum($cols), $array0, $array1, $array2)
);
PHP Snippet 11:
array (
0 => 8,
1 => 18,
2 => 26,
3 => 34,
4 => 42,
5 => 50,
)