note 32907 added to ref.array
| From: | danvk at rice dot edu | Date: | Tue, 10 Jun 2003 15:48:00 +0000 |
| Subject: | note 32907 added to ref.array | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-50112@lists.php.net to get a copy of this message | ||
A note on the + and += operators for arrays: If there are duplicate keys, then no
'addition' takes place at all. For example, Array(1,2,3)+Array(4,5,6)=Array(1,2,3). If you
want to numerically add two arrays, try out this function:
# Recursively add (numerically) the contents of two arrays
function addArrays( $a, $b ){
$ret = $a;
foreach( $b as $key => $val ){
if (is_array($val))
$ret[$key]=addArrays( $ret[$key], $val );
else
$ret[$key]+=$val;
}
return $ret;
}
It behaves just like the + and += operators, except when there's an overlap between the arrays.
So
$a=Array(Array(1,2),3,4);
$b=Array(10,20),30,40);
print_r(addArrays($a, $b));
will produce Array(Array(11,22),33,44), as you'd expect. Of course, the arrays do need to have
the same structure--if a key is an array in one and a scalar in the other, you'll run into
trouble.
----
Manual Page -- http://www.php.net/manual/en/ref.array.php
Edit Note -- http://master.php.net/manage/user-notes.php?action=edit+32907
Delete Note -- http://master.php.net/manage/user-notes.php?action=delete+32907&report=yes
Reject Note -- http://master.php.net/manage/user-notes.php?action=reject+32907&report=yes