Re: [PHP] Sum two arrays

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



*This message was transferred with a trial version of CommuniGate(tm) Pro*
I'm not sure if Larry Realized that his indexes don't match.... $a = indexes
01, 02, 04 and $b = indexes 01, 03, 05?

Assuming both indexes are the same(which would make sense because you want
to add them together).

see:
http://www.phpexamples.net/modules.php?name=Code_Exchange&func=viewSnippet&s
nippetId=19

As long ast the array indexes match, you shouldn't have and problems, and if
one of the array indexes doesn't have anything, it will still add... just
add 0.

Rolf Brusletto
rolf@phpExamples.net
PHP/MySQL Coder
Security Admin
http://www.phpExamples.net

----- Original Message -----
From: "Jason k Larson" <jlarson@candlefire.org>
To: <Larry_Li@amat.com>
Cc: <php-general@lists.php.net>
Sent: Saturday, April 12, 2003 1:42 AM
Subject: Re: [PHP] Sum two arrays


> *This message was transferred with a trial version of CommuniGate(tm) Pro*
> I'm sure there is a cleaner, better way ... but here's how I did it in 1
> minute.
>
> $a = array("01"=>10,"02"=>20,"04"=>40);
> $b = array("01"=>10,"03"=>30,"05"=>50);
> $c = array();
>
> foreach ($a as $idx => $val)
> {
>          if (isset ($c[$idx])) { $c[$idx] = $c[$idx] + $a[$idx]; }
>          else { $c[$idx] = $a[$idx]; }
> }
> foreach ($b as $idx => $val)
> {
>          if (isset ($c[$idx])) { $c[$idx] = $c[$idx] + $b[$idx]; }
>          else { $c[$idx] = $b[$idx]; }
> }
>
> HTH,
> Jason k Larson
>
>
> Larry_Li@amat.com wrote:
> > $a=array("01"=>10,"02"=>20,"04"=>40);
> > $b=array("01"=>10,"03"=>30,"05"=>50);
> >
> >
> > $c=$a+$b;
> >
> > $c=array("01"=>20,"02"=>20,"03"=>30,"04"=>40,"05"=>50);
> >
> > Thanks,
> > Larry
> >
> >
> >
> >
>
>
>
> --
> PHP General Mailing List (http://www.php.net/)
> To unsubscribe, visit: http://www.php.net/unsub.php
>
>


-- 
PHP Database Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php


[Index of Archives]     [PHP Home]     [PHP Users]     [Postgresql Discussion]     [Kernel Newbies]     [Postgresql]     [Yosemite News]

  Powered by Linux