Will Barangi Will Barangi - 2 months ago 7
PHP Question

how to update an array using a function, php

Hey I have return a function that takes some orders and subtracts them from an array of inventory...however when am running the function it is only updating the inventory within the function and the original inventory doesn't change..I know this is something to do with scope but I don't know how to do it exactly..
How can I do this ? can you help?

function updateInventory ($inv) {
foreach($_SESSION["inventory"] as $bookDetails) {
foreach($_POST['orders'] as $k => $v) {
if($bookDetails['title'] == $k && $v == "hardcover") {
$bookDetails['hc-quantity']=intval($bookDetails['hc-quatinty'])-1;
}
}
}
}

Answer

When you assign an array to a variable, it gets a copy of the array, so changes to that variable don't affect the original array. You can use a reference to prevent copying.

function updateInventory ($inv) {
    foreach($_SESSION["inventory"] as &$bookDetails) {
        foreach($_POST['orders'] as $k => $v) {
            if($bookDetails['title'] == $k && $v == "hardcover") {
                $bookDetails['hc-quantity']--;     
            }      
        }
    }
}