Forum Moderators: coopster

Message Too Old, No Replies

adding sums of array values

a tricky one?

         

httpwebwitch

8:55 pm on Jul 15, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



I have two arrays:
('a'=>1,'b'=>3,'c'=>2,'d'=>6)
('a'=>2,'b'=>0,'c'=>4)

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.
:-)

httpwebwitch

9:13 pm on Jul 15, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



function add_array_values($a,$b){
$new=array();
foreach($a as $k=>$v){
$new[$k]+=$v;
}
foreach($b as $k=>$v){
$new[$k]+=$v;
}
return $new;
}

Is that as good as it gets?

Netizen

10:29 pm on Jul 15, 2004 (gmt 0)

10+ Year Member



Or:

function add_array_values($a,$b){

$keys=array_merge(array_keys($a),array_keys($b));

foreach ($keys as $key) {
$c[$key]=$a[$key]+$b[key];
}

return $c;

}

Is there another way of presenting the data in the arrays? Where are the arrays being generated?

ergophobe

10:53 pm on Jul 15, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



Some deconstructive criticism....

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.

ergophobe

11:05 pm on Jul 15, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



To be more constructive...

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);