If you were working on a PHP shopping cart using SESSION variables for the cart item's product id and quantity, how would you update the cart if the same product were chosen? If the same product id was posted, how would you add the quantities and show just the same product?

    One way would be to use the unique ID of the product in question as an array key within $_SESSION, e.g.$_SESSION['cart'][1234512]. Then if a user added another item, I might do something like:

    if(isset($_SESSION['cart'][$itemID]['quantity'])) {
      $_SESSIONP['cart'][$itemID]['quantity'] = $_SESSION['cart'][$itemID]['quantity'] + $_POST['quantity'];
    } else {
      $_SESSIONP['cart'][$itemID]['quantity'] = $_POST['quantity'];
    }
    

      I'm doing something like that. My quantity is updating when I add the same product but I need to delete the product that's the last item in the SESSION array. So far I've tried array_pop and unset but I can't get rid of the non-updated product.

      These two don't work to remove the last product added to the session:

      unset($SESSION["cart_item"]["element_id"]);
      array_pop($
      SESSION["cart_item"]);

        I'm confused. Are you saying the cart can only ever have one item? Why do you want to remove the "last" item when a user adds another one? Perhaps we need to see exactly what array structure you're using for $_SESSION and what the "before" and "after" contents should be in each case you want to handle?

          I'm presuming this is because the "Old" item has quantity N, and the new one has quantity N+1, and (s)he is replacing the old entry with the new one instead of modifying the original entry's quantity.

            Write a Reply...