Compare two associative arrays by key I am currently for a program I am writing needing to compare two associative arrays by key and value in PHP and get the common elements as well as the difference between the common elements.

I have currently arrived at the following solution:

&lt;?php
$newArr = [0 =&gt; ['id' =&gt; 'UT5', 'qty' =&gt; '4'], 1 =&gt; ['id' =&gt; 'WRO', 'qty' =&gt; '3'], 2 =&gt; ['id' =&gt; 'SHO', 'qty' =&gt; '3']];

$oldArr = [0 =&gt; ['id' =&gt; 'SHO', 'qty' =&gt; '1'], 1 =&gt; ['id' =&gt; 'UT5', 'qty' =&gt; '2'], ];

$newReset = [];
foreach( $newArr as $item ) {
    $newReset[$item['id']] = $item['qty'];
}

$oldReset = [];
foreach( $oldArr as $item ) {
    $oldReset[$item['id']] = $item['qty'];
}

foreach( $newReset as $key =&gt; $val ) {
    if( isset( $oldReset[$key] ) ) {
        $toAdd[$key] = max( $oldReset[$key], $val ) - min( $oldReset[$key], $val );
    }
    else $toAdd[$key] = intval($val);
}

var_dump( $toAdd );


I am just curious as to how I can go about implementing perhaps array functions or an array function with a closure etc... to refactor the approach or use another method entirely?

For reference, my output is currently as follows:

array(3) {  ["UT5"]=> int(2)  ["WRO"]=> int(3)  ["SHO"]=> int(2) }

Any help is appreciated.

Thanks!
You can reduce your code in several ways.

First, since you seem to want the absolute value of the difference between qtys for the same ìd`:

$toAdd[$key] = max( $oldReset[$key], $val ) - min( $oldReset[$key], $val );


It can be achieved more simply:

$toAdd[$key] = abs($oldReset[$key] - $val);


BTW, when id doesn't exist in $oldReset you probably want the same, so you should use $toAdd[$key] = abs($val); instead of $toAdd[$key] = intval($val); (but maybe you are sure that qty is always positive).

On the other hand, you're preparing both $newArr and $oldArr to get a simplified version of the form array(id =&gt; qty): you can do it for only one array, so using less code and probably working faster.  

With all the changes proposed above, your whole code becomes:

$oldReset = [];
foreach ($oldArr as $item) {
  $oldReset[$item['id']] = $item['qty'];
}
foreach ($newArr as $key =&gt; $val) {
  $id = $val['id'];
  $qty = $val['qty'];
  if (isset($oldReset[$id])) {
    $toAdd[$id] = abs($oldReset[$id] - $qty);
  }
  else {
    $toAdd[$id] = abs($qty);
  }
}


Last point, I notice that you don't try to detect ids existing in $oldArray and not present in $newArray. But again maybe you're sure it cannot happen.