Posted by ZeldorBlat on 01/03/06 18:55
Gerard Matthew wrote:
> I'm looking for a short way of suming the indexes of two arrays and
> returning one array as the result. I'm not referring to what
> array_sum() is capable of doing. Below will get it done; but is there
> any built in function doing the same??
Not that I know of.
> function sum_by_index($array1,$array2) {
> for ($i = 0; $i <= (count($array1) -1); $i++) {
> $temp[$i] = $array1[$i] + $array2[$i];
> }
>
> return $temp;
> }//note both $array1 and $array2 are to be of the same size
>
Nothing wrong with that. Although it might be slightly more efficient
as such:
function sum_by_index(&$array1, &$array2) {
for($i = (count($array1) - 1); $i >= 0; $i++)
$temp[$i] = $array1[$i] + $array[$i];
return $temp;
}
Navigation:
[Reply to this message]
|