EDIT: Calculating the difference between 2 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[5] = 20;
 $array1[6] = 50;

 $array2[6] = 60;
 $array2[7] = 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[5] = -20; // NULL - $array1[5]
$arraydiff[6] =  10; // $array2[6] - $array1[6]
$arraydiff[7] =  30; // $array2[7] - 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];

this results to

array(3) { [6]=> int(10) [7]=> int(30) [5]=> 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;?

  • 2
    \$\begingroup\$ 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. \$\endgroup\$ – Mathieu Guindon Nov 16 '16 at 16:01
  • 2
    \$\begingroup\$ @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 \$\endgroup\$ – Accountant م Nov 16 '16 at 18:20
  • 1
    \$\begingroup\$ 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! \$\endgroup\$ – Mathieu Guindon Nov 16 '16 at 18:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.