note 79795 added to language.operators.array

From: Date: Thu, 13 Dec 2007 09:42:40 +0000
Subject: note 79795 added to language.operators.array
Groups: php.notes 
Request: Send a blank email to php-notes+get-133412@lists.php.net to get a copy of this message
Simple array arithmetic: If you want to add or subtract the elements at identical keys... <?php function array_add($a1, $a2) { // ... // adds the values at identical keys together $aRes = $a1; $aRays = func_get_args(); for ($i=1;$i<sizeof($aRays);++$i) { $aRay = $aRays[$i]; foreach ($aRay as $key => $val) if (array_key_exists($key, $aRes)) $aRes[$key] += $aRay[$key]; $aRes += $aRay; } return $aRes; } function array_subtract($a1, $a2) { // ... // subtracts the values at identical keys from the corresponding value in $a1 $aRes = $a1; $aRays = func_get_args(); for ($i=1;$i<sizeof($aRays);++$i) { $aRay = $aRays[$i]; foreach ($aRay as $key => $val) { if (array_key_exists($key, $aRes)) $aRes[$key] -= $aRay[$key]; else $aRes[$key] = -$aRay[$key]; } } return $aRes; } Example: $a1 = array(9, 8, 7); $a2 = array(1=>7, 6, 5); $a3 = array(2=>5, 4, 3); $aSum = array_add($a1, $a2, $a3); $aDiff = array_subtract($a1, $a2, $a3); // $aSum => [9, 15, 18, 9, 3] // $aDiff => [9, 1, -4, -9, -3] ?> To make a similar function, array_concatenate(), change the first += only in array_add() to .= Csaba Gabor from Vienna ---- Server IP: 192.35.244.50 Probable Submitter: 80.108.23.194 ---- Manual Page -- http://www.php.net/manual/en/language.operators.array.php Edit -- https://master.php.net/note/edit/79795 Del: integrated -- https://master.php.net/note/delete/79795/integrated Del: useless -- https://master.php.net/note/delete/79795/useless Del: bad code -- https://master.php.net/note/delete/79795/bad+code Del: spam -- https://master.php.net/note/delete/79795/spam Del: non-english -- https://master.php.net/note/delete/79795/non-english Del: in docs -- https://master.php.net/note/delete/79795/in+docs Del: other reasons-- https://master.php.net/note/delete/79795 Reject -- https://master.php.net/note/reject/79795 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#133412) next »