Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

nhayder's avatar
Level 13

cart session with multiple product options not working

I have a cart session on my store app where a user can add multiple product and each product has multiple options or variations.

an example of this would be a black iPhone with 246 GB RAM so the customer can customize product by choosing color and extras like RAM's

this is the class that I have so far

class Cart
{
    public $items = [];
    public $totalQty;
    public $totalPrice;

    public function __Construct($cart = null) {
        if($cart) {
            $this->items = $cart->items;
            $this->totalQty = $cart->totalQty;
            $this->totalPrice = $cart->totalPrice;
        } else {
            $this->items = [];
            $this->totalQty = 0;
            $this->totalPrice = 0;
        }
    }

    public function add($product) {
        
         $item = [
             'id' => $product->id,
             'name' => $product->name,
             'slug' => $product->slug,
             'price' => $product->price,
             'qty' => 0,
             'poster' => $product->poster,
            'options' => [ // this is where i loop throught these option in checkout page
                $product->color => array(
                        'qty' => $product->qty,
                        'color' => $product->color,
                        'variation' => $product->variation,
                        'variation_price' => $product->variation_price,
                    )
            ]
         ];

         if( !array_key_exists($product->id, $this->items)) {
             array_push($this->items[$product->id], array('qty' => $product->qty,
                        'color' => $product->color,
                        'variation' => $product->variation,
                        'variation_price' => $product->variation_price,));

             $this->totalQty +=1;
             $this->totalPrice += $product->price * $product->qty; 
         } else {
             $this->totalQty +=1 ;
             $this->totalPrice += $product->price * $product->qty; 
         }

         $this->items[$product->id]['qty']  += $product->qty ;
    // }

The problem I'm facing is when a user adds same product to cart with deferent option (LIKE red iPhone with 512 GB RAM ), in this case I need to add the additional extra options to the options array so i can loop thought them in the checkout page????

with the implementation above I'm able to add new fresh products with their optional extra variations to cart, but its not able to add extra options to existing products

any ideas on how to fix this issue ???

0 likes
0 replies

Please or to participate in this conversation.