0

it is possible to add a key value in array following my example

$a = array( '1' => '5', '2' => '7', '3' => '1');

now i will add more array key value like this

$b = array( '1' => '5', '2' => '2');

Now i want output like this sum of same key

$c = array( '1' => '10', '2' => '9', '3' => '1');

if i want to remove array like this out put

$c = array( '1' => '7', '2' => '9', '3' => '1');
Patel
  • 543
  • 4
  • 20
  • Your question is in confused manner. You should explain, what is the scenario and what you are trying to get and what error it is throwing. – Savan Koradia Jun 09 '14 at 13:06

3 Answers3

2

Like this for subtracting.

$minus = array('1'=>3);
foreach($minus as $k => $v){
   if(isset($c[$k])){
       $c[$k]-= $v;
   }else{
       $c[$k] = -$v;
   }
}

And this for adding:

$add = array('1'=>3);
foreach($add as $k => $v){
   if(isset($add[$k])){
       $c[$k]+= $v;
   }else{
       $c[$k] = $add[$k];
   }
}

Of course, you could wrap these in functions and have them set the new array to something different to prevent overwriting the old data.

Jonathan
  • 585
  • 7
  • 27
2
function array_add($a, $b){
    foreach ($b as $key => $value) {
        if(isset($a[$key]) && is_numeric($a[$key])){
            $a[$key] += $value;
        }
    }
    return $a;
}

function array_subtract($a, $b){
    foreach ($b as $key => $value) {
        if(isset($a[$key]) && is_numeric($a[$key])){
            $a[$key] -= $value;
        }
    }
    return $a;
}
Steve
  • 20,703
  • 5
  • 41
  • 67
0

How to "add" a and b:

foreach($a as $key => $value) {
    if(isset($b[$key])) {
        $c[$key] = $a[$key] + $b[$key];
    } else {
        $c[$key] = $a[$key];
    }
}

This will however ignore indexes that are in b but not in a.

kajacx
  • 12,361
  • 5
  • 43
  • 70