I made this function to calculate the difference between 2 arrays and return it in a third array. I'm using this function as a part of stocktaking functionality I apply in my accounting system.
function stockdiff ($array2,$array1){
//inputs :
//$array2 is the stocktaking result in an array that has the format "$product_id=>$quantity"
//$array1 is the stock according to the data in the system in an array that has the format "$product_id=>$quantity"
foreach($array2 as $key=> $value){
if(isset($array1[$key])){$result[$key] = $array2[$key] - $array1[$key];}
else{$result[$key] = $array2[$key];}
}
$array1diff = array_diff_key($array1,$array2);
foreach($array1diff as $key=> $value){
$result[$key] = -1 * $array1[$key];
}
return $result;
}
Case example
When the user do the stocktaking, its result are going to be saved in $array2
in the format $product_id=>$quantity
.
This is a stocktaking result example:
$array2[2] = 500;
$array2[3] = 7;
$array2[1] = 302;
$array2[105] = 7000;
$array2[7] = 304;
$array2[8] = 20;
$array2[9] = 20;
$array2[11] = 20;
$array2[73] = 32;
$array2[21] = 35;
I then compare it against the stock quantities according to the data in the system $array1
which might be something like this:
$array1[1] = 30;
$array1[2] = 60;
$array1[3] = 202;
$array1[4] = 200;
$array1[7] = 0;
$array1[8] = 0;
$array1[9] = 0;
$array1[11] = 52;
$array1[21] = 70;
$array1[99] = 21;
I made this function to do that job. I need it to tell me the changes that happened for every product between the data in the system and the actual data come from the stocktaking, for example, let's take product_id 2
.
In the system it was $array1[2] = 60;
60 units from the product 2, and the stocktaking told us no, we found 500 units from the product 2 $array2[2] = 500;
. So, the function must return [2]=>440
.
The function also needs to consider about these points:
- If there is a product in the stocktaking array ($array2) that has no matching product in the stock-in-system array($array1), then the function will assume it's whole quantity has been increased and return it's quantity from
$array2
. - If there is a product in the stock-in-system array ($array1) that has no matching product in the stocktaking array (
$array2
), then the function will assume it's whole quantity has been decreased and return-1 * quantity
.
What do you think about the function?