note 84024 added to language.operators.array

From: Date: Tue, 24 Jun 2008 15:54:14 +0000
Subject: note 84024 added to language.operators.array
Groups: php.notes 
Request: Send a blank email to php-notes+get-140773@lists.php.net to get a copy of this message
Simple array arithmetic: A more compact way of adding or subtracting the elements at identical keys... <?php function array_add($a1, $a2) { // ... // adds the values at identical keys together $aRes = $a1; foreach (array_slice(func_get_args(), 1) as $aRay) { foreach (array_intersect_key($aRay, $aRes) as $key => $val) $aRes[$key] += $val; $aRes += $aRay; } return $aRes; } function array_subtract($a1, $a2) { // ... // adds the values at identical keys together $aRes = $a1; foreach (array_slice(func_get_args(), 1) as $aRay) { foreach (array_intersect_key($aRay, $aRes) as $key => $val) $aRes[$key] -= $val; foreach (array_diff_key($aRay, $aRes) as $key => $val) $aRes[$key] = -$val; } 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 only the first of the two '+=' in array_add() to '.=' Csaba Gabor from Vienna ---- Server IP: 81.223.48.75 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/84024 Del: integrated -- https://master.php.net/note/delete/84024/integrated Del: useless -- https://master.php.net/note/delete/84024/useless Del: bad code -- https://master.php.net/note/delete/84024/bad+code Del: spam -- https://master.php.net/note/delete/84024/spam Del: non-english -- https://master.php.net/note/delete/84024/non-english Del: in docs -- https://master.php.net/note/delete/84024/in+docs Del: other reasons-- https://master.php.net/note/delete/84024 Reject -- https://master.php.net/note/reject/84024 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#140773) next »