-1

I have two arrays inventoryStock and posStock (point of sale stock) they both use product sku numbers as the key and the value is the quantity on hand I need to somehow update the posStock with the values from $inventoryStock where there keys are matching.

Examples of arrays:

inventoryStock{
   abs-0098 => 5,
   abs-0099 => 23,
   abs-0100 => 8,
   abs-0101 => 19
}

posStock{
 abs-0098 => 5,
 abs-0099 => 23,
 abs-0101 => 15
}

I need the posStock to be the same as the inventoryStock I cannot just make posStock be inventory stock becasue inventory stock has extra products not listed in the Point of sale.

2 Answers2

2

You can use array union.

The + operator returns the right-hand array appended to the left-hand array; for keys that exist in both arrays, the elements from the left-hand array will be used, and the matching elements from the right-hand array will be ignored.

In your case (if I understand the spec correctly):

$newPOSStock = $inventoryStock + $posStock;
Jason McCreary
  • 71,546
  • 23
  • 135
  • 174
  • 1
    Just for completion sake, this is exactly opposite of array_merge where keys in the left array are overwritten by keys in the right array(s). Sometimes you want to keep the values on the left and use `+` and sometimes you want to keep the values on right and use array_merge. – Jonathan Kuhn Jan 14 '15 at 18:37
  • Indeed. Thanks @Jonathan Kuhn. – Jason McCreary Jan 14 '15 at 18:38
1

You are looking for the array_key_exists() function of PHP.

foreach ($inventoryStock as $key => $value) {
      if (array_key_exists($key, $posStock)) {
        $posStock[$key] = $value;
        continue; // Continue Loop
      }
      // Do something if the array key doesn't exist.
    }

To expand on why I would do it this way. I now have a logic block to allow me to do something if the array key doesn't exist like add it to the PosStock, or if I want to or change values of other variables to trigger other behaviors.

Richard Christensen
  • 2,046
  • 17
  • 28