You are here: Re: sum two arrays by indexes « PHP Programming Language « IT news, forums, messages
Re: sum two arrays by indexes

Posted by Ken Robinson on 01/03/06 18:51

Gerard Matthew wrote (in part):
> 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??
>
> 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

The following function does the same as yours with the added
functionality that it works with associative arrays also:

function sum_by_index($ary1,$ary2)
{
$tmp = array();
foreach($ary1 as $k=>$v) $tmp[$k] = $v + $ary2[$k];
return($tmp);
}

In your function, why do you use

for ($i = 0; $i <= (count($array1) -1); $i++)

when

for ($i = 0; $i < count($array1); $i++)

works just as well (and almost everyone else uses it).

Ken

 

Navigation:

[Reply to this message]


Удаленная работа для программистов  •  Как заработать на Google AdSense  •  England, UK  •  статьи на английском  •  PHP MySQL CMS Apache Oscommerce  •  Online Business Knowledge Base  •  DVD MP3 AVI MP4 players codecs conversion help
Home  •  Search  •  Site Map  •  Set as Homepage  •  Add to Favourites

Copyright © 2005-2006 Powered by Custom PHP Programming

Сайт изготовлен в Студии Валентина Петручека
изготовление и поддержка веб-сайтов, разработка программного обеспечения, поисковая оптимизация