Vortex
Vortex

Reputation: 816

PHP Compare two multidimensional arrays by key and value

I am busy learning PHP and was looking for a way to compare two associative arrays by both key and value and then find the difference of the two i.e.

If I had an associative array with:

array (size=2)
  'x15z' => int '12' (length=2)
  'x16z' => int '3' (length=1)

And another with the following:

array (size=1)
  'x15z' => int 1

I am trying to find the difference between the two associative arrays and I am currently trying to use array_diff_assoc($array1, $array2) and this works in the case whereby one element is missing from the other however in the instance described above, the difference is

array (size=2)
  'x15z' => int '12' (length=2)
  'x16z' => int '3' (length=1)

as opposed to what I am looking for which is:

array (size=2)
  'x15z' => int '11' (length=2)
  'x16z' => int '3' (length=1)

Whereby the value difference is also calculated.

Is there any logical way to calculate the difference of two associative arrays based upon their keys and values? Thanks!

Upvotes: 4

Views: 8772

Answers (1)

HenryTK
HenryTK

Reputation: 1287

function calculateDifference($array1, $array2){
  $difference = array();
  foreach($array1 as $key => $value){
    if(isset($array2[$key])){
      $difference[$key] = abs($array1[$key] - $array2[$key]);
    }else{
      $difference[$key] = $value;
    }
  }
  foreach($array2 as $key => $value){
    if(isset($array1[$key])){
      $difference[$key] = abs($array1[$key] - $array2[$key]);
    }else{
      $difference[$key] = $value;
    }
  }
  return $difference;
}

Upvotes: 4

Related Questions