Simple array arithmetic:
A more compact way of adding or subtracting the elements at identical keys...
<?php
function array_add($a1, $a2) { $aRes = $a1;
foreach (array_slice(func_get_args(), 1) as $aRay) {
foreach (array_intersect_key($aRay, $aRes) as $key => $val) $aRes[$key] += $val;
$aRes += $aRay; }
return $aRes; }
function array_subtract($a1, $a2) { $aRes = $a1;
foreach (array_slice(func_get_args(), 1) as $aRay) {
foreach (array_intersect_key($aRay, $aRes) as $key => $val) $aRes[$key] -= $val;
foreach (array_diff_key($aRay, $aRes) as $key => $val) $aRes[$key] = -$val; }
return $aRes; }
Example:
$a1 = array(9, 8, 7);
$a2 = array(1=>7, 6, 5);
$a3 = array(2=>5, 4, 3);
$aSum = array_add($a1, $a2, $a3);
$aDiff = array_subtract($a1, $a2, $a3);
?>
To make a similar function, array_concatenate(), change only the first of the two '+=' in array_add() to '.='
Csaba Gabor from Vienna