Forum Moderators: coopster
I need a very efficient function to add the values together for each element. For instance, the output would be an array:
('a'=>3,'b'=>3,'c'=>6,'d'=>6)
This function could potentially be used in billions of iterations, so it needs to be as efficient as possible.
I will also be needing another similar function, which I'll post in a separate thread. Any advice is welcome.
:-)
Assuming that you are running your development platform with error reporting set to all (which is a good idea):
$new[$k]+=$v;
This will throw a notice or warning, since $new[$k] is not defined on the first time through.
$c[$key]=$a[$key]+$b[key];
Similar problem here. You will get a warning or notice for an undefined index.
Of course, if speed is to be valued over stability, these two options are both fine.
If you decide that you want this to be as solid as possible, you could benchmark the following two alternatives and see which is better:
option 1
$keys=array_merge(array_keys($a),array_keys($b));
$new=array();
foreach($keys as $k=>$v){
$new[$k]=0;
}
foreach($a as $k=>$v){
$new[$k]+=$v;
}
foreach($b as $k=>$v){
$new[$k]+=$v;
}
return $new;
}
**** option 2 (I assume this will be slower).
function add_array_values($a,$b){
$keys=array_merge(array_keys($a),array_keys($b));
foreach ($keys as $key) {
$x = (isset($a[$key]))? $a[$key] : 0;
$y = (isset($b[$key]))? $b[$key] : 0;
$c[$key]=$x + $y;
}
return $c;
}
Incidentally, to combine this with another thread [webmasterworld.com], to get the difference, you just do the same, but instead of
$c[$key]=$x + $y;
Use
$c[$key]= abs($x - $y);