Posts

Showing posts with the label session-variables

Updating Values in A Multidimensional Cart Array

Updating Values in A Multidimensional Cart Array I am writing a custom shopping cart in PHP, I add product info to the cart session like this: $product_array=array($title,$price,$qty); if(!isset($_SESSION['cart'])) $_SESSION['cart']=array(); if(!in_array($product_array,$_SESSION['cart'])) $_SESSION['cart']=$product_array; else { // update price and quantity here } My challenge: I want to update the price and quantity($qty) of the product if it already exists in $_SESSION['cart'] array rather than adding it. Something like this price = price + $price, qty = qty + $qty 1 Answer 1 This example is similar to your example. you can add code from foreach loop in else condition. I am considering product_id instead of $title variable. $_SESSION['cart'] = [ 'product_id'=> 12, 'price' => 100 , 'quantity' => 2 ]; $_SESSION['...