note 32907 deleted from ref.array by sniper

From: Date: Sat, 18 Oct 2003 18:00:40 +0000
Subject: note 32907 deleted from ref.array by sniper
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-58820@lists.php.net to get a copy of this message
Note Submitter: danvk@rice.edu ---- 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.

« previous php.notes (#58820) next »