Search code examples
phparrayscart

Php cart array check if item is already added


I'm trying to develop a e-commerce application with a shopping cart using mostly php and jquery.

I need to compare a selected item (id, sku, size, and color) to items already in an array. If the item already exists in the array, then increase the amount by the amount of the chosen item.

Meaning:

  1. Client clicks on an item "add to cart"
  2. Client clicks the item again
  3. PHP function checks if the newly added item exists in array, if it exists increase amount, if not push into array

Solution

  • You can write code something like this.

    $cart = $_SESSION['cart'];
    
    /*
     * If product already exist into the cart then update QTY of product
     * Othewise add new product into the cart
     */
    if(isset($cart[$product['id']])):
        $cart[$product['id']]['qty'] += 1;
    else:
        $cart[$product['id']] = $product;
        $cart[$product['id']]['qty'] = 1;
    endif;
    
    $_SESSION['cart'] = $cart;