0

I have array like below in my session

Array ( 
    [product-2] => Array ( 
        [product_name] => Hello 
        [pid] => 2 
        [product_price] => 300 
        [quantity] => 1 
        [product_image] => 1630037523.png 
    ) 
) 

I am looking for change value for field called quantity.

I am searching like below

if (isset($_POST['action']) && $_POST['action']=="change"){
    
    foreach($_SESSION["shopping_cart"] as $key => $value) {
        
        if('product-'.$_POST["pid"] == $key){
            echo "found";
            $new_quantity = $_POST['quantity'];
            //now do not know how to update it in array
            break;

        }
    
    }   
    
}

I am new in PHP and does not know how to update in my array. Let me know if anyone here can help me for same. Thanks!

3
  • Update it with: $_SESSION["shopping_cart"][$key]['quantity'] = $new_quantity;. Btw, is there a reason why you're prefixing the key with product- instead of just using the id straight off? Just seems like extra fluff for no gain. Commented Aug 28, 2021 at 2:41
  • @MagnusEriksson Thanks a lot, its working fine. since my id is like 1,2,3,4 etc, it was causing some issue so I have added product- prefix. Thanks a lot! Commented Aug 28, 2021 at 2:45
  • What do you mean by "causing some issue"? In what way? I don't see any reason why it wouldn't work. Commented Aug 28, 2021 at 2:48

1 Answer 1

1

There's no need to iterate through the array. You can just check if the product exist and update the quantity directly:

if (isset($_POST['action']) && $_POST['action']=="change") {
    $key = 'product-' . $_POST['pid'];

    // Check if the product exists in the array and update the quantity if it does
    if (isset($_SESSION['shopping_cart'][$key])) {
        $_SESSION['shopping_cart'][$key]['quantity'] = $_POST['quantity'];
    }        
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.