Reputation: 1160
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
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
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
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
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