note 90136 added to function.array-merge

From: Date: Tue, 07 Apr 2009 19:58:35 +0000
Subject: note 90136 added to function.array-merge
Groups: php.notes 
Request: Send a blank email to php-notes+get-152923@lists.php.net to get a copy of this message
I was looking to merge two associative arrays together, adding the values together if the keys were the same. If there were keys unique to either array, these would be added into the merged array with their existing values. I couldnt find a function to do this, so made this: <?php function merge($array1, $array2) { if(sizeof($array1)>sizeof($array2)) { echo $size = sizeof($array1); }else{ $a = $array1; $array1 = $array2; $array2 = $a; echo $size = sizeof($array1); } $keys2 = array_keys($array2); for($i = 0;$i<$size;$i++) { $array1[$keys2[$i]] = $array1[$keys2[$i]] + $array2[$keys2[$i]]; } $array1 = array_filter($array1); return $array1; } ?> Enter in two arrays to the function, then the output will be both arrays merged together with values added if keys are the same. ---- Server IP: 87.124.35.190 Probable Submitter: 86.11.175.235 ---- Manual Page -- http://www.php.net/manual/en/function.array-merge.php Edit -- https://master.php.net/note/edit/90136 Del: integrated -- https://master.php.net/note/delete/90136/integrated Del: useless -- https://master.php.net/note/delete/90136/useless Del: bad code -- https://master.php.net/note/delete/90136/bad+code Del: spam -- https://master.php.net/note/delete/90136/spam Del: non-english -- https://master.php.net/note/delete/90136/non-english Del: in docs -- https://master.php.net/note/delete/90136/in+docs Del: other reasons-- https://master.php.net/note/delete/90136 Reject -- https://master.php.net/note/reject/90136 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#152923) next »