Harry12345
Harry12345

Reputation: 1160

Subtract corresponding values from one associative array from another associative array; removing elements which have a zero value

I have 2 associative arrays, like below.

Array
(
    [Turbine] => 0
    [Nuts and Bolts] => 6
    [Runner Blade] => 5
)
Array
(
    [Nuts and Bolts] => 10
    [Runner Blade] => 5
    [Turbine] => 1
)

What I want to do is compare the two arrays and return ones that have the same key but a different value. Similar to array_intersect_assoc(), but that returns all values that match which is not what I want. Using the examples above what I want to return is the difference between the 2 values, something like:

Array
(
    [Nuts and Bolts] => 4
    [Turbine] => 1
)

Upvotes: -2

Views: 1561

Answers (5)

mickmackusa
mickmackusa

Reputation: 48031

If you don't mind mutating the second array, then performing some conditional arithematic and unsetting will get the job done.

Code: (Demo)

$new = [
    'Turbine' => 0,
    'Nuts and Bolts' => 6,
    'Runner Blade' => 5
];
$old = [
    'Nuts and Bolts' => 10,
    'Runner Blade' => 5,
    'Turbine' => 1
];

foreach ($old as $k => &$v) {
    if (empty($new[$k])) {
        continue;          // ignore if key not in $new array or is zero
    }
    $v -= $new[$k];        // subtract new value from old value
    if (!$v) {
        unset($old[$k]);   // if old value has become zero, unset it
    }
}
var_export($old);

Upvotes: 0

Edward Lee
Edward Lee

Reputation: 951

$diff = array_diff_assoc($arr1, $arr2);

$result = array();

foreach(array_keys($diff) as $key){
    $result[$key] = abs($arr1[$key] - $arr2[$key]);
}

var_dump($result);

Upvotes: 0

MH2K9
MH2K9

Reputation: 12039

Try this...

$newArr = array();
foreach($arr1 as $k=>$v){
    $dif = abs($arr1[$k] - $arr2[$k]);
    if($dif) $newArr[$k] = $dif;
}
print '<pre>';
print_r($newArr);

Upvotes: 1

u_mulder
u_mulder

Reputation: 54796

Something like this:

$ar1;
$ar2;

foreach ($ar1 as $k => $v) {
    if (intval($ar2[$k]) != intval($v))
        $ar1[$k] = abs($v - $ar2[$k]);
    else
        unset($ar1[$k]);    // remove key with equal value
}

Upvotes: 2

user1009835
user1009835

Reputation:

This will do what you want:

array_intersect_key($array1, $array2)

Upvotes: 0

Related Questions