phparraysassociative-arrayinteger-arithmeticarray-intersect

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
)

Solution

  • 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);