# Calculating the difference between two (incomplete) arrays

I'm coding PHP for only 4 months, and I need your help to improve this code

I have 2 arrays like this

//array1
$array1 = 20;$array1 = 50;

//array2
$array2 = 60;$array2 = 30;


Now I need to get the difference between the values of each key between array2 and array1 i.e $array2 -$array1 (if this is legal)

So, I need the result array difference to be like this

$arraydiff = -20; // NULL -$array1
$arraydiff = 10; //$array2 - $array1$arraydiff =  30; // $array2 - NULL  I got this done by doing that foreach($array2 as $key=>$value){
//check if the key exists only in array2 or in both arrays
if(isset($array1[$key])){$result[$key] = $array2[$key] - $array1[$key];}
else{$result[$key] = $array2[$key];}
}

//get the keys that exist in array1 but not in array2
$array1diff = array_diff_key($array1,$array2); foreach($array1diff as $key=>$value){
$result[$key] = -1 * $array1[$key];
}
var_dump($result);  this results to array(3) { => int(10) => int(30) => int(-20) }  Is there any better way or PHP built-in tools to get this done instead of that. Can't I do for example $result = $array2 -$array1;?

• This code was originally posted on Stack Overflow, where boiling the code down to a specific issue is the norm. However on Code Review things are different; please take a moment to read our help center, and a guide to CR for SO users. Don't give us "something like this", give us your real, actual, working code - keep in mind that reviewers will be commenting on any & all aspects of the code. – Mathieu Guindon Nov 16 '16 at 16:01
• @Mat'sMug yes, that exactly what happened with me when I posted this on stackover flow. I'm very interested now in code review, I guess this site exactly what I was looking for, I'm not a professional programmer, and I always wish if there are experts can review my codes when I finish them and give me their comments. I'm reading the help center now to know exactly what type of question you need to be posted, and I'm going to edit this question. HOW come I never heard of code review, I'm so happy I found this site – Accountant م Nov 16 '16 at 18:20
• For the record, reading that comment has just made my day. I'll be sharing it in The 2nd Monitor (the site's main chat) - feel free to join the regulars anytime! – Mathieu Guindon Nov 16 '16 at 18:29