Why doesn't my array get updated. Let's say I store 2 items Shoes and Shirt, and I get something like this.
Array
(
[0] => Array
(
[item_id] => 1
[item_name] => shoes
[item_price] => 10
[item_quantity] => 10
)
[1] => Array
(
[item_id] => 2
[item_name] => Shirt
[item_price] => 5
[item_quantity] => 5
)
)
And that's fine. But if I pass 1 and 4 to getItem function it echoes out remaining items as it should, 6 in this case, but if I check the $inventoryItems array it still says there are 10 Shoes. And if I pass again 1 and 4 it will give the same result, 6, but it should return 2.
class Inventory{
public $inventoryItems = [];
public function storeItem($item){
$this->inventoryItems[] = [
'item_id' => $item->itemId,
'item_name' => $item->itemName,
'item_price' => $item->itemPrice,
'item_quantity' => $item->itemQuantity
];
}
public function inventoryList(){
print_r($this->inventoryItems);
}
public function getItem($itemId, $itemQuantity){
foreach($this->inventoryItems as $inventoryItem){
if($inventoryItem['item_id'] === $itemId && $inventoryItem['item_quantity'] > 0){
$inventoryItem['item_quantity'] -= $itemQuantity;
echo $inventoryItem['item_quantity'] . ' ' .
$inventoryItem['item_name'] . " remaining.
";
}
}
}
}
foreach($this->inventoryItems as $inventoryItem){
is creating a copy of each inventoryItem
and storing it in $inventoryItem
. You can change it to:
foreach($this->inventoryItems as &$inventoryItem){
to get a reference to the inventory item, and then the changes will happen in the original.